﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SYcwpb.Access;
using SYcwpb.Helpers;
using SYcwpb.Views;
using SYcwpb.Models;
using SYcwpb.Commands;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Collections;
using SYcwpb.ViewModels.DataProvider;
using System.Data;
using SYcwpb.Controls;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.Windows;
using System.Threading;
using System.Windows.Media;
using SYcwpb.WinForm;
using Helpers;

namespace SYcwpb.ViewModels
{
    enum ParametersSubType
    {
        bc_first,//起点便乘
        bc_last,//终点便乘
        unmorning_bc,//白/夜班出勤便乘
        unnight_bc_out,//非夜班出勤便乘
        early_back_garage,//夜班提前回库便乘
        meal_cross_road//顶饭圈交路设置
    }
    class CrossingRoadViewModel : ViewModelBase, IDataErrorInfo
    {

        private const string NEXT_TRAIN_TAG = "--->";

        private WriteLog log;
        /// <summary>
        /// 标识是否已经存在该时刻表的交路表
        /// </summary>
        public bool _isCrossRoadIn = false;

        private string _lineID = CONSTDATA.UserModel.Line;
        private string _lunchCrossRoadCount = "1";
        private string _supperCrossRoadCount = "2";
        private string _garageAhead = "60";
        private string _garageBCAhead = "30";
        private string _normalAhead = "15";

        private string _restTime = "10";
        private string _mealRestTime = "30";
        private string _changeStation = "";

        private string _garageDelay = "20";
        private string _bcGarageDelay = "5";
        private string _normalDelay = "3";

        private DataTable dtCrossingRoadParameters = null;

        private const int Max_UnMornigBcNum = 4;
        private const int MAX_PhoneAttendOutMaxNum = 8;
        //private const int Max_EarlyBackNum = 5;
        private const int Max_SetMealNum = 4;
        private Visibility _exportInfoVisibility = Visibility.Collapsed;

        private ObservableCollection<TimeTableModel> _timeTableCollections = null;
        private TimeTableAccess _timeTableAccess = new TimeTableAccess();
        private CrossingRoadAccess _crossingRoadAccess = new CrossingRoadAccess();
        private StatisticsAccess _statisticsAccess = new StatisticsAccess();
        private CrossingRoadColorConfigAccess _crossingRoadColorConfigAccess = new CrossingRoadColorConfigAccess();

        private TimeTableModel _timeTable = new TimeTableModel();

        public Dictionary<string, int> Group = new Dictionary<string, int>();

        public Thread ExportExcelThread = null;
        private string filePath = "";
        private bool _isExporting = false;

        double _outMiles = 0;
        double _inMiles = 0;

        private bool _isDraftVersion;
        public bool IsDraftVersion
        {
            get
            {
                return _isDraftVersion;
            }
            set
            {
                _isDraftVersion = value;
                OnPropertyChanged("IsDraftVersion");
            }
        }

        /// <summary>
        /// 1号线：十三号街 -> 黎明广场
        /// 2号线：全运路 -> 三台子
        /// </summary>
        double _totalMiles = 0;

        /// <summary>
        /// 1号线：十三号街 -> 启工街
        /// 2号线：三台子 -> 青年大街
        /// </summary>
        double _upToChangedMiles = 0;

        /// <summary>
        /// 1号线:黎明广场 -> 启工街
        /// 2号线：全运路 -> 青年大街
        /// </summary>
        double _downToChangedMiles = 0;

        /// <summary>
        /// 2号线：HKH -> 青年大街
        /// </summary>
        double _hKHUpToChangedMiles = 0;

        /// <summary>
        /// 2号线： 全运路 -> HKH
        /// </summary>
        double _hKHTotalMiles = 0;

        private static Color DefaultColor = Colors.Tan;
        private static double DefaultMax = 99999.0;

        public ColorConfig _warnColorConfig = new ColorConfig();

        Regex rx = new Regex(@"^[^-]?\d+\d*$");

        private DataTable Kilometersdt;
        private DataTable KilometersOutAndIndt;
        SqlDataLayer sql_Help = new SqlDataLayer();

        /// <summary>
        /// 早班出库车集合
        /// </summary>
        public ObservableCollection<string> ZBTrainList = new ObservableCollection<string>();

        /// <summary>
        /// 该时刻表对应所有车次的集合，包括 车次号，发车时间，到达换班站的时间，结束时间。用于交路表编辑
        /// </summary>
        public static ObservableCollection<SmallTrain> TrainList = new ObservableCollection<SmallTrain>();

        public static Dictionary<string, SmallTrain> TrainDictionary = new Dictionary<string, SmallTrain>();

        private CrossingRoadView _crossingRoadView;
        private ICommand _add_PhoneAttend_Command;
        private ICommand _add_UnMorningBC_Command;
        private ICommand _add_UnNightBC_Out_Command;
        private ICommand _add_Unplan_Out_Command;
        private ICommand _add_EarlyBackGarageCommand;
        private ICommand _setMealCommand;
        private ICommand _generateCommand;
        private ICommand _addDefaultRoadsCommand;
        private ICommand _checkCommand;
        private ICommand _saveCommand;
        private ICommand _saveDraftCommand;
        private ICommand _exportCommand;
        private ICommand _exportTimeTableCommand;
        private ICommand _dg_MenuItem_Command;
        private ICommand _warnColorCommand;
        private ICommand _numberSortCommand;
        private ICommand _planTimeSortCommand;

        /// <summary>
        /// 休息时间排交路对象
        /// </summary>
        GenerateCrossingRoad generateCrossingRoad = null;

        GenerateCrossingRoadByBCNum generateCrossingRoadByBCNum = null;

        private CrossingRoadObjects _crossingRoadZB = new CrossingRoadObjects();
        private CrossingRoadObjects _crossingRoadBB = new CrossingRoadObjects();
        private CrossingRoadObjects _crossingRoadYB = new CrossingRoadObjects();

        private List<CrossingRoadObjects> classList = new List<CrossingRoadObjects>();


        private CrossRoadEditor _crossRoadEditor;

        private CrossingRoadColorConfigView _crossingRoadColorConfigView;

        /// <summary>
        /// 正在被编辑的交路集合
        /// </summary>
        private string EditingCls = null;

        /// <summary>
        /// 正在执行的编辑操作：Add ，Edit
        /// </summary>
        private string EditingAction = null;

        /// <summary>
        /// 正在被编辑的行
        /// </summary>
        private CrossingRoadObject EditingRow = null;

        public string LineID
        {
            get
            {
                return _lineID;
            }
        }
        private string _lastModifiedTime;
        public string LastModifiedTime
        {
            get { return _lastModifiedTime; }
            set
            {
                _lastModifiedTime = value;
                OnPropertyChanged("LastModifiedTime");
            }
        }
        private string _lastModifier;
        public string LastModifier
        {
            get { return _lastModifier; }
            set
            {
                _lastModifier = value;
                OnPropertyChanged("LastModifier");
            }
        }

        public string FirstRoundID
        {
            get
            {
                if (_lineID == "1")
                    return "02";
                else if (_lineID == "2")
                    return "01";
                else
                    return null;
            }
        }

        public ObservableCollection<TimeTableModel> TimeTableCollections
        {
            get
            {
                //if (null == _timeTableCollections)
                //    _timeTableCollections = _timeTableAccess.GetFileList();

                return _timeTableCollections;
            }
        }

        public ObservableCollection<EarlyBackGarageModel> _earlyBackGarageCollections = new ObservableCollection<EarlyBackGarageModel>();
        public ObservableCollection<EarlyBackGarageModel> EarlyBackGarageCollections
        {
            get
            {
                return _earlyBackGarageCollections;
            }
        }

        public ObservableCollection<UnMoringBCModel> _unMorningBCCollections = new ObservableCollection<UnMoringBCModel>();
        public ObservableCollection<UnMoringBCModel> UnMorningBCCollections
        {
            get
            {
                return _unMorningBCCollections;
            }
        }


        public ObservableCollection<TrainIdModel> _phoneAttendOutCollections = new ObservableCollection<TrainIdModel>();
        public ObservableCollection<TrainIdModel> PhoneAttendOutCollections
        {
            get
            {
                return _phoneAttendOutCollections;
            }
        }
        public ObservableCollection<TrainIdModel> _unplanCollections = new ObservableCollection<TrainIdModel>();
        public ObservableCollection<TrainIdModel> UnplanCollections
        {
            get
            {
                return _unplanCollections;
            }
        }

        public ObservableCollection<UnNightBCOutModel> _unNightBC_OutCollections = new ObservableCollection<UnNightBCOutModel>();
        public ObservableCollection<UnNightBCOutModel> UnNightBC_OutCollections
        {
            get { return _unNightBC_OutCollections; }
        }

        public ObservableCollection<SetMealCrossRoadModel> _setMealCrossRoalCollections = new ObservableCollection<SetMealCrossRoadModel>();
        public ObservableCollection<SetMealCrossRoadModel> SetMealCrossRoalCollections
        {
            get { return _setMealCrossRoalCollections; }
        }


        private ObservableCollection<string> _bBFirstOutTrains = new ObservableCollection<string>();
        /// <summary>
        /// 白班出库车集合，用于电话退勤交路的首车次选择
        /// </summary>
        public ObservableCollection<string> BBFirstOutTrains
        {
            get { return _bBFirstOutTrains; }
            set
            {
                _bBFirstOutTrains = value;
                OnPropertyChanged("BBFirstOutTrains");
            }
        }

        private string _phoneOutTrain;
        public string PhoneOutTrain
        {
            get { return _phoneOutTrain; }
            set
            {
                if (value != _phoneOutTrain)
                    _phoneOutTrain = value;

                OnPropertyChanged("PhoneOutTrain");
            }
        }

        private ObservableCollection<string> _nightBackTrains = new ObservableCollection<string>();
        /// <summary>
        /// 夜班回库车次集合，用于初始化夜班提前便乘回库的选择
        /// </summary>
        public ObservableCollection<string> NightBackTrains
        {
            get { return _nightBackTrains; }
            set
            {
                _nightBackTrains = value;
                OnPropertyChanged("NightBackTrains");
            }
        }

        private string _nightEmptyTrain;
        public string NightEmptyTrain
        {
            get { return _nightEmptyTrain; }
            set
            {
                if (value != _nightEmptyTrain)
                    _nightEmptyTrain = value;

                OnPropertyChanged("NightEmptyTrain");
            }
        }

        private bool _is_NightMeal_BC;
        public bool Is_NightMeal_BC
        {
            get { return _is_NightMeal_BC; }
            set
            {
                if (value != _is_NightMeal_BC)
                    _is_NightMeal_BC = value;

                OnPropertyChanged("Is_NightMeal_BC");
            }
        }

        public TimeTableModel TimeTable
        {
            get { return _timeTable; }
            set
            {
                if (_timeTable == value)
                {
                    return;
                }

                _timeTable = (TimeTableModel)value;

                OnPropertyChanged("TimeTable");
            }
        }



        public string TxtBCLast
        {
            get
            {
                if (_lineID == "1")
                    return "便乘至黎明广场站人数：";
                else if (_lineID == "2")
                    return "便乘至三台子、航空天大站、蒲田路站人数：";
                else
                    return null;
            }
        }

        public string TxtBCLastRoad
        {
            get
            {
                if (_lineID == "1")
                    return "选择便乘到黎明广场站车次号：";
                else if (_lineID == "2")
                    return "选择便乘到三台子、航空天大站、蒲田路站车次号：";
                else
                    return null;
            }
        }

        public string TxtBCFirstRoad
        {
            get
            {
                if (_lineID == "1")
                    return "选择便乘到十三号街站车次号：";
                else if (_lineID == "2")
                    return "选择便乘到全运路站车次号：";
                else
                    return null;
            }
        }

        public string TxtBCFist
        {
            get
            {
                if (_lineID == "1")
                    return "便乘至十三号街站人数：";
                else if (_lineID == "2")
                    return "便乘至全运路站人数：";
                else
                    return null;
            }
        }

        public string LunchCrossRoadCount
        {
            get { return _lunchCrossRoadCount; }
            set
            {
                if (_lunchCrossRoadCount == value)
                    return;
                _lunchCrossRoadCount = value;

                OnPropertyChanged("LunchCrossRoadCount");
            }
        }

        public string SupperCrossRoadCount
        {
            get { return _supperCrossRoadCount; }
            set
            {
                if (_supperCrossRoadCount == value)
                    return;
                _supperCrossRoadCount = value;

                OnPropertyChanged("SupperCrossRoadCount");
            }
        }

        public string GarageAhead
        {
            get { return _garageAhead; }
            set
            {
                if (_garageAhead == value)
                    return;
                _garageAhead = value;

                OnPropertyChanged("GarageAhead");
            }
        }

        public string GarageBCAhead
        {
            get { return _garageBCAhead; }
            set
            {
                if (_garageBCAhead == value)
                    return;
                _garageBCAhead = value;

                OnPropertyChanged("GarageBCAhead");
            }
        }

        public string NormalAhead
        {
            get { return _normalAhead; }
            set
            {
                if (_normalAhead == value)
                    return;
                _normalAhead = value;

                OnPropertyChanged("NormalAhead");
            }
        }

        public string NormalDelay
        {
            get { return _normalDelay; }
            set
            {
                if (_normalDelay == value)
                    return;
                _normalDelay = value;

                OnPropertyChanged("NormalDelay");
            }
        }

        public string GarageDelay
        {
            get { return _garageDelay; }
            set
            {
                if (_garageDelay == value)
                    return;
                _garageDelay = value;

                OnPropertyChanged("GarageDelay");
            }
        }

        public string BcGarageDelay
        {
            get
            {
                return _bcGarageDelay;
            }
            set
            {
                if (_bcGarageDelay == value)
                    return;
                _bcGarageDelay = value;
                OnPropertyChanged("BcGarageDelay");
            }
        }

        public string ChangeStation
        {
            get
            {
                if (_lineID == "1")
                {
                    return "启工街站";
                }
                else if (_lineID == "2")
                {
                    return "青年大街站";
                }
                else
                    return null;
            }
            set { ;}
        }

        public string RestTime
        {
            get { return _restTime; }
            set
            {
                if (_restTime == value)
                    return;

                _restTime = value;
                OnPropertyChanged("RestTime");
            }
        }

        public string MealRestTime
        {
            get { return _mealRestTime; }
            set
            {
                if (_mealRestTime == value)
                    return;

                _mealRestTime = value;
                OnPropertyChanged("MealRestTime");
            }
        }


        public bool IsExporting
        {
            get { return !_isExporting; }
            set
            {
                if (value == _isExporting)
                    return;

                _isExporting = value;

                OnPropertyChanged("IsExporting");
            }
        }

        public Visibility ExportInfoVisibility
        {
            get { return _exportInfoVisibility; }
            set
            {
                if (value == _exportInfoVisibility)
                    return;

                _exportInfoVisibility = value;

                OnPropertyChanged("ExportInfoVisibility");
            }
        }

        public string Error { get { return null; } }

        public string this[string columnName]
        {
            get
            {
                string error = null;
                error = ValidateTime(columnName);
                return error;
            }
        }


        public CrossingRoadObjects CrossingRoadZB
        {
            get { return _crossingRoadZB; }
            set
            {
                if (value == _crossingRoadZB)
                    return;

                _crossingRoadZB = value;
                OnPropertyChanged("CrossingRoadZB");
            }
        }

        public CrossingRoadObjects CrossingRoadBB
        {
            get { return _crossingRoadBB; }
        }

        public CrossingRoadObjects CrossingRoadYB
        {
            get { return _crossingRoadYB; }
        }

        public ICommand Add_UnMorningBC_Command
        {
            get
            {
                if (null == _add_UnMorningBC_Command)
                {
                    _add_UnMorningBC_Command = new RelayCommands(
                        para => this.Add_UnMorningBC_Command_Method()
                        );
                }
                return _add_UnMorningBC_Command;
            }
        }
        public ICommand Add_PhoneAttendOut_Command
        {
            get
            {
                if (null == _add_PhoneAttend_Command)
                {
                    _add_PhoneAttend_Command = new RelayCommands(
                        para => this.Add_PhoneAttendOutCommand_method()
                        );
                }
                return _add_PhoneAttend_Command;
            }
        }
        public ICommand Add_UnNightBC_Out_Command
        {
            get
            {
                if (null == _add_UnNightBC_Out_Command)
                {
                    _add_UnNightBC_Out_Command = new RelayCommands(
                        para => this.Add_UnNightBC_Out_Command_Method()
                        );
                }
                return _add_UnNightBC_Out_Command;
            }
        }
        public ICommand Add_Unplan_Out_Command
        {
            get
            {
                if (null == _add_Unplan_Out_Command)
                {
                    _add_Unplan_Out_Command = new RelayCommands(
                        para => this.Add_UnplanCommand_method()
                        );
                }
                return _add_Unplan_Out_Command;
            }
        }
        public ICommand Add_EarlyBackGarageCommand
        {
            get
            {
                if (null == _add_EarlyBackGarageCommand)
                {
                    _add_EarlyBackGarageCommand = new RelayCommands(
                        para => this.Add_EarlyBackGarageCommand_Method(),
                        para => this.CanAdd_EarlyBackGarage()
                        );
                }
                return _add_EarlyBackGarageCommand;
            }
        }

        public ICommand SetMealCommand
        {
            get
            {
                if (null == _setMealCommand)
                {
                    _setMealCommand = new RelayCommands(
                        para => this.SetMealCommand_Method(),
                        para => this.CanSetMealCommand()
                        );
                }
                return _setMealCommand;
            }
        }

        public ICommand GenerateCommand
        {
            get
            {
                if (null == _generateCommand)
                {
                    _generateCommand = new RelayCommands(
                        para => this.GenerateCrossingRoadMethod(),
                        para => this.CanGenerate()
                        );
                }
                return _generateCommand;
            }
        }
        private ICommand _saveParametersCommand;
        public ICommand SaveParametersCommand
        {
            get
            {
                if (null == _saveParametersCommand)
                {
                    _saveParametersCommand = new RelayCommands(
                        para => this.SaveParametersMethod()
                        );
                }
                return _saveParametersCommand;
            }
        }

        public ICommand AddDefaultRoadsCommand
        {
            get
            {
                if (null == _addDefaultRoadsCommand)
                {
                    _addDefaultRoadsCommand = new RelayCommands(para => this.AddDefaultRoadsCommand_Method()
                        , para => this.Can_AddDefaultRoadsCommand_Method());
                }
                return _addDefaultRoadsCommand;
            }
        }

        public ICommand ExportCommand
        {
            get
            {
                if (null == _exportCommand)
                {
                    _exportCommand = new RelayCommands(para => this.ExportCommand_Method()
                        , para => this.Can_ExportCommand_Method());
                }
                return _exportCommand;
            }
        }

        public ICommand ExportTimeTableCommand
        {
            get
            {
                if (null == _exportTimeTableCommand)
                {
                    _exportTimeTableCommand = new RelayCommands(para => this.ExportTimeTable_Method()
                        , para => this.Can_ExportCommand_Method());
                }
                return _exportTimeTableCommand;
            }
        }

        private ICommand _saveAsCommand;
        public ICommand SaveAsCommand
        {
            get
            {
                if (null == _saveAsCommand)
                    _saveAsCommand = new RelayCommands(para => this.SaveAs());
                return _saveAsCommand;
            }
        }
        public ICommand CheckCommand
        {
            get
            {
                if (null == _checkCommand)
                    _checkCommand = new RelayCommands(para => this.Check());
                return _checkCommand;
            }
        }
        public ICommand SaveCommand
        {
            get
            {
                if (null == _saveCommand)
                {
                    _saveCommand = new RelayCommands(para => this.Save());
                }
                return _saveCommand;
            }
        }
        public ICommand NumberSortCommand
        {
            get
            {
                if (null == _numberSortCommand)
                    _numberSortCommand = new RelayCommands(para => NumberSort(para));
                return _numberSortCommand;
            }
        }
        public ICommand PlanTimeSortCommand
        {
            get
            {
                if (null == _planTimeSortCommand)
                    _planTimeSortCommand = new RelayCommands(para => PlanTimeSort(para));
                return _planTimeSortCommand;
            }
        }
        private void NumberSort(object classtype)
        {
            int ct = Convert.ToInt32(classtype);
            CrossingRoadObjects list = null;
            switch (ct)
            {
                case 0:
                    list = this._crossingRoadZB;
                    break;
                case 2:
                    list = this._crossingRoadBB;
                    break;
                case 3:
                    list = this._crossingRoadYB;
                    break;
                default:
                    return;
            }
            list.NumberSort();
            UpdateIndex("All");
        }
        private void PlanTimeSort(object classtype)
        {
            int ct = Convert.ToInt32(classtype);
            CrossingRoadObjects list = null;
            switch (ct)
            {
                case 0:
                    list = this._crossingRoadZB;
                    list.ZBSort();
                    break;
                case 2:
                    list = this._crossingRoadBB;
                    list.Sort();
                    break;
                case 3:
                    list = this._crossingRoadYB;
                    list.Sort();
                    break;
                default:
                    return;
            }

            UpdateIndex("All");
        }
        public ICommand SaveDraftCommand
        {
            get
            {
                if (null == _saveDraftCommand)
                {
                    _saveDraftCommand = new RelayCommands(para => this.Save());
                }
                return _saveDraftCommand;
            }
        }

        public ICommand Dg_MenuItem_Command
        {
            get
            {
                if (null == _dg_MenuItem_Command)
                    _dg_MenuItem_Command = new RelayCommands(para => Dg_MenuItem_Command_Method(para));

                return _dg_MenuItem_Command;
            }
        }
        private ICommand _dg_MenuItem_Merge_Command;
        public ICommand Dg_MenuItem_Merge_Command
        {
            get
            {
                if (null == _dg_MenuItem_Merge_Command)
                    _dg_MenuItem_Merge_Command = new RelayCommands(para => this.Dg_MenuItem_Merge_Command_Method());
                return _dg_MenuItem_Merge_Command;
            }
        }
        public ICommand WarnColorCommand
        {
            get
            {
                if (null == _warnColorCommand)
                    _warnColorCommand = new RelayCommands(para => this.WarnColorCommand_Method());

                return _warnColorCommand;
            }
        }

        public string _averageMilesZB = "0.00";
        public string AverageMilesZB
        {
            get { return _averageMilesZB; }
            set
            {
                if (value == _averageMilesZB)
                    return;

                _averageMilesZB = value;
                OnPropertyChanged("AverageMilesZB");
            }
        }

        public string _averageWhoursZB = "0.00";
        public string AverageWhoursZB
        {
            get { return _averageWhoursZB; }
            set
            {
                if (value == _averageWhoursZB)
                    return;

                _averageWhoursZB = value;
                OnPropertyChanged("AverageWhoursZB");
            }
        }

        public string _averageMilesBB = "0.00";
        public string AverageMilesBB
        {
            get { return _averageMilesBB; }
            set
            {
                if (value == _averageMilesBB)
                    return;

                _averageMilesBB = value;
                OnPropertyChanged("AverageMilesBB");
            }
        }

        public string _averageWhoursBB = "0.00";
        public string AverageWhoursBB
        {
            get { return _averageWhoursBB; }
            set
            {
                if (value == _averageWhoursBB)
                    return;

                _averageWhoursBB = value;
                OnPropertyChanged("AverageWhoursBB");
            }
        }

        public string _averageMilesYB = "0.00";
        public string AverageMilesYB
        {
            get { return _averageMilesYB; }
            set
            {
                if (value == _averageMilesYB)
                    return;

                _averageMilesYB = value;
                OnPropertyChanged("AverageMilesYB");
            }
        }

        public string _averageWhoursYB = "0.00";
        public string AverageWhoursYB
        {
            get { return _averageWhoursYB; }
            set
            {
                if (value == _averageWhoursYB)
                    return;

                _averageWhoursYB = value;
                OnPropertyChanged("AverageWhoursYB");
            }
        }

        public CrossingRoadViewModel()
        {
            try
            {
                this._crossingRoadView = CrossingRoadView._view;

                InitGroup();

                InitMilesParameters();

                _crossingRoadZB.UpdateAverageEvent += new EventHandler<UpdateArgs>(_crossingRoadZB_UpdateAverageEvent);
                _crossingRoadBB.UpdateAverageEvent += new EventHandler<UpdateArgs>(_crossingRoadBB_UpdateAverageEvent);
                _crossingRoadYB.UpdateAverageEvent += new EventHandler<UpdateArgs>(_crossingRoadYB_UpdateAverageEvent);

                classList.Add(_crossingRoadZB);
                classList.Add(_crossingRoadBB);
                classList.Add(_crossingRoadYB);
            }
            catch (System.Exception ex)
            {

            }
        }

        void _crossingRoadYB_UpdateAverageEvent(object sender, UpdateArgs e)
        {
            this.AverageMilesYB = e.AverageMiles;
            this.AverageWhoursYB = e.AverageWhours;
        }

        void _crossingRoadBB_UpdateAverageEvent(object sender, UpdateArgs e)
        {
            this.AverageMilesBB = e.AverageMiles;
            this.AverageWhoursBB = e.AverageWhours;
        }

        void _crossingRoadZB_UpdateAverageEvent(object sender, UpdateArgs e)
        {
            this.AverageMilesZB = e.AverageMiles;
            this.AverageWhoursZB = e.AverageWhours;
        }

        public void InitGroup()
        {
            DataTable dt = _crossingRoadAccess.GetGroupType();
            Group.Clear();
            if (null != dt && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Group.Add(dt.Rows[i]["grp_type"].ToString(), Convert.ToInt32(dt.Rows[i]["ID"]));
                }
            }
        }

        private void InitMilesParameters()
        {
            DataTable paraDT = _statisticsAccess.GetParaMeters();
            if (null == paraDT || paraDT.Rows.Count < 1)
            {
                MessageBoxHelper.ShowError("获取公里数、工时统计参数时出现异常，请仔细检查公里数自动生成处结果是否正确！");
                return;
            }

            _inMiles = Convert.ToDouble(paraDT.Rows[0]["InMiles"]);
            _outMiles = Convert.ToDouble(paraDT.Rows[0]["OutMiles"]);
            _totalMiles = Convert.ToDouble(paraDT.Rows[0]["TotalMiles"]);
            _upToChangedMiles = Convert.ToDouble(paraDT.Rows[0]["UpToChangedMiles"]);
            _downToChangedMiles = Convert.ToDouble(paraDT.Rows[0]["DownToChangedMiles"]);

            _hKHUpToChangedMiles = Convert.ToDouble(paraDT.Rows[0]["HKHUpToChangedMiles"]);
            _hKHTotalMiles = Convert.ToDouble(paraDT.Rows[0]["HKHTotalMiles"]);
        }

        private void InitCrossingRoadObjects()
        {
            try
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("执行CrossingRoadObjects");
                if (null == generateCrossingRoadByBCNum)
                    return;
                _crossingRoadZB.Clear();
                _crossingRoadBB.Clear();
                _crossingRoadYB.Clear();

                log = new WriteLog(string.Format("{0} - CrossingRoad.txt", TimeTable.Name));

                log.WriteLine(DateTime.Now.ToString() + "*************\n");

                GetNewKilometersdt();

                for (int i = 0; i < generateCrossingRoadByBCNum.crossingRoadCollections.Count; i++)
                {
                    CrossingRoad road = generateCrossingRoadByBCNum.crossingRoadCollections[i] as CrossingRoad;
                    if (road.Items.Count < 1)
                        continue;

                    //OutPutRoad(road, i.ToString());

                    ClassType currentClass = road._ClassType;

                    CrossingRoadModel row = CrossingRoadModel.CreateCrossingRoadModel();

                    Train repTrain;
                    int planT = -1;
                    int offT = -1;

                    if (road.is_bc_first || road.is_bc_last)
                    {
                        repTrain = road.bc_train;
                        row.RepTrain = "(便)" + repTrain.TrainID;
                    }
                    else
                    {
                        repTrain = road.Items[0] as Train;
                        row.RepTrain = repTrain.TrainID;
                    }

                    if (null != repTrain)
                    {
                        row.TrainTime = GlobalVariables.FormatTime(road.BeginTime.ToString());

                        planT = GetPlanTime(road);
                        row.PlanTime = GlobalVariables.FormatTime(planT.ToString());

                        if (road._OutPlace == AttendOutPlace.Garage)
                            offT = road.EndTime + Convert.ToInt32(_garageDelay) * 60;  //车辆段退勤增加*分钟
                        else
                            offT = road.EndTime + Convert.ToInt32(_normalDelay) * 60;  //车辆段退勤增加*分钟

                        if (offT < 7200)
                            offT += 86400;
                        

                        row.OffTime = GlobalVariables.FormatTime(offT.ToString());

                        row.Whours = Math.Round((double)(offT - planT) / 3600, 2).ToString();

                        row.AttenPlace = GetAttendOutPlace(road._AttendPlace);
                        row.OffPlace = GetAttendOutPlace(road._OutPlace);

                        row.Miles = GetMiles(road);
                        row.StringCrossingRoad = GetRunTrain(road);

                        if (string.IsNullOrEmpty(road.BCBackGarageTrainID))  //不是夜班便乘回库的
                            row.OffTrain = road.GetLastTrain().TrainID;
                        else
                        {
                            row.OffTrain = road.BCBackGarageTrainID;
                            row.BCBackGarageTrainID = road.BCBackGarageTrainID;
                            if (road._OutPlace == AttendOutPlace.MidSta)
                                row.Notes += string.Format("便 {0} 退勤", row.OffTrain);
                            else
                                row.Notes += string.Format("便 {0} 回库", row.OffTrain);
                        }

                        if (road.is_bb_phoneout)
                            row.Notes += "电话退勤";

                        if (road._ClassType == ClassType.Night)
                        {
                            row.lastTrainTime = GlobalVariables.FormatTime(road.GetLastTrain().EndTime.ToString());
                        }
                    }

                    if (road.is_meal_road)
                    {
                        row.Notes = "顶饭圈";
                    }
                    var item = new CrossingRoadObject(row);
                    if (currentClass == ClassType.Morning)
                    {
                        _crossingRoadZB.Add(item);
                        item.CrossingRoadCol = _crossingRoadZB;
                    }
                    if (currentClass == ClassType.Day)
                    {
                        _crossingRoadBB.Add(item);

                        item.CrossingRoadCol = _crossingRoadBB;
                    }
                    if (currentClass == ClassType.Night)
                    {
                        _crossingRoadYB.Add(item);
                        item.CrossingRoadCol = _crossingRoadYB;
                    }
                }

                UpdateIndex("All");

                log.Close();
                MessageBoxHelper.ShowTips("交路生成成功");
            }
            catch (Exception ex)
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
            }
        }

        public void GetNewKilometersdt()
        {
            string str = "select * from NewKilometers where LineID='" + CONSTDATA.UserModel.Line + "'";
            Kilometersdt = sql_Help.SelectDt(str);
            string str2 = "select * from NewOutAndInKilometers where LineID='" + CONSTDATA.UserModel.Line + "'";
            KilometersOutAndIndt = sql_Help.SelectDt(str2);
            if (KilometersOutAndIndt.Rows.Count > 0)
            {
                _outMiles = int.Parse(KilometersOutAndIndt.Rows[0]["OutKilometers"].ToString());
                _inMiles = int.Parse(KilometersOutAndIndt.Rows[0]["InKilometers"].ToString());
            }
        }

        public void OutPutRoad(CrossingRoad road, string index)
        {
            log.WriteLine(string.Format("交路 {0} ：", index));
            for (int i = 0; i < road.Items.Count; i++)
            {
                string Id = (road.Items[i] as Train).TrainID;
                log.Write(Id);
                if (road.LunchTrain == Id || road.DinerTrain == Id)
                {
                    log.Write(" 【饭】 ");
                }
                if (i != road.Items.Count - 1)
                {
                    log.Write(" --> ");
                }
            }

            log.WriteLine("");
        }

        public int GetPlanTime(CrossingRoad road)
        {
            if (road._ClassType == ClassType.Morning)
            {
                if (road.is_bc_first || road.is_bc_last)
                    return road.BeginTime - Convert.ToInt32(_garageBCAhead) * 60;
                else
                    return road.BeginTime - Convert.ToInt32(_garageAhead) * 60;
            }
            else if (road._ClassType == ClassType.Day || road._ClassType == ClassType.Night)
            {
                //if (road._AttendPlace == AttendOutPlace.MidSta)  //中途站出勤的
                if (road._AttendPlace == AttendOutPlace.Garage)
                    return road.BeginTime - Convert.ToInt32(_garageAhead) * 60;
                else
                    return road.BeginTime - Convert.ToInt32(_normalAhead) * 60;
            }
            else
                return -1;
        }

        public Train GetRepTrain(CrossingRoad road, GroupType type)
        {
            Train result = null;

            if (type == GroupType.Morning)
            {
                foreach (Train train in road.Items)
                {
                    if (train.group == GroupType.Morning || train.group == GroupType.Morning_Day)
                    {
                        result = train;
                        break;
                    }
                }
            }
            else if (type == GroupType.Day)
            {
                foreach (Train train in road.Items)
                {
                    if (train.group == GroupType.Day || train.group == GroupType.Morning_Day || train.group == GroupType.Day_Night)
                    {
                        result = train;
                        break;
                    }
                }
            }
            else if (type == GroupType.Night)
            {
                foreach (Train train in road.Items)
                {
                    if (train.group == GroupType.Night || train.group == GroupType.Day_Night)
                    {
                        result = train;
                        break;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取交路字符串
        /// </summary>
        /// <param name="road"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public string GetRunTrain(CrossingRoad road)
        {
            string result = "";

            for (int i = 0; i < road.Items.Count; i++)
            {

                Train _trian = road.Items[i] as Train;

                if (_trian.TrainID == "10405")
                {
                    string err = "";
                }
                result += _trian.TrainID;
                if (i == 0 && !(road.is_bc_last || road.is_bc_first))  //白班和夜班的首班车时间
                {
                    if (_trian.TimeAtFstSta > road.BeginTime)
                    {
                        if (road._AttendPlace == AttendOutPlace.MidSta)
                            result += "(" + GlobalVariables.FormatTime(_trian.TimeLeaveChangePoint.ToString()) + ",";
                        else
                            result += "(" + GlobalVariables.FormatTime(_trian.TimeAtFstSta.ToString()) + ",";
                    }
                    else
                        result += "(" + GlobalVariables.FormatTime(road.BeginTime.ToString()) + ",";
                }
                else
                {
                    if (_trian.TimeAtFstSta > road.BeginTime)
                        result += "(" + GlobalVariables.FormatTime(_trian.TimeAtFstSta.ToString()) + ",";
                    else
                        result += "(" + GlobalVariables.FormatTime(_trian.BeginTime.ToString()) + ",";
                }

                if (i == road.Items.Count - 1 && string.IsNullOrEmpty(road.BCBackGarageTrainID)) //每个交路最后一班车的处理
                {
                    if (_trian.TimeAtLstSta < road.EndTime && !_trian.IsLastTrip)
                        result += GlobalVariables.FormatTime(_trian.TimeAtLstSta.ToString()) + ")";
                    else
                        result += GlobalVariables.FormatTime(road.EndTime.ToString()) + ")";
                }
                else
                {
                    if (_trian.TimeAtLstSta < road.EndTime && !_trian.IsLastTrip)
                        result += GlobalVariables.FormatTime(_trian.TimeAtLstSta.ToString()) + ")";
                    else
                        result += GlobalVariables.FormatTime(_trian.EndTime.ToString()) + ")";
                }

                if (road.LunchTrain == _trian.TrainID || road.DinerTrain == _trian.TrainID)
                {
                    result += "[饭]";

                }
                if (_trian.IsLastTrip)
                    result += "[库]";
                result += NEXT_TRAIN_TAG;
            }

            if (!string.IsNullOrEmpty(result))
            {
                //if (road.is_bc_last || road.is_bc_first)
                //    result = result.Insert(0, "(便)");
                result = result.Remove(result.Length - 4);
            }
            return result;
        }

        public string GetMiles(CrossingRoad road)
        {
            //设置公里数
            double miles = 0;
            string firstT = road.GetFirstTrain().TrainID;
            string lastT = road.GetLastTrain().TrainID;

            if (firstT == "21803")
            {
                string err = "";
            }

            if (LineID == "1") //原本一号线和二号线统计公里数逻辑一致，但是加站后分开计算，以后如果可以合并一起，请合并  modifed by pyl 2013/12/14
            {
                if (road._AttendPlace == AttendOutPlace.Garage && !road.is_bc_first && !road.is_bc_last)
                    miles += _outMiles;
                if (road._OutPlace == AttendOutPlace.Garage && string.IsNullOrEmpty(road.BCBackGarageTrainID))
                    miles += _inMiles;

                for (int i = 0; i < road.Items.Count; i++)
                {
                    Train train = road.Items[i] as Train;
                    AttendOutPlace start;
                    AttendOutPlace end;
                    if ((train.IsLastTrip && road._OutPlace == train.EndPlace) || i < road.Items.Count - 1 || road._ClassType == ClassType.Night)
                    {
                        end = train.EndPlace;
                    }
                    else
                    {
                        end = road._OutPlace;
                    }
                    if (i == 0 && road._ClassType != ClassType.Morning && !train.IsFirstOut)
                    {
                        start = road._AttendPlace;
                    }
                    else
                    {
                        start = train.StartPlace;
                    }
                    miles += getline2miles2(start, end);
                    //miles += getline2miles(train.StartPlace, train.EndPlace);
                    //if ((train.IsLastTrip && road._OutPlace == train.EndPlace) || i < road.Items.Count - 1 || road._ClassType == ClassType.Night)
                    //{
                    //    miles += getline2miles2(train.StartPlace, train.EndPlace);
                    //} else if (i==0&& road._ClassType != ClassType.Morning&&!train.IsFirstOut) {
                    //    miles += getline2miles2(road._AttendPlace, train.EndPlace);
                    //}
                    //else
                    //    miles += getline2miles2(train.StartPlace, road._OutPlace);

                    //miles += getline2miles(train.StartID, train.EndID);
                }
                //miles = road.Items.Count * _totalMiles;

                //if (road._AttendPlace == AttendOutPlace.Garage && !road.is_bc_first && !road.is_bc_last)
                //    miles += _outMiles;
                //else if (road._AttendPlace == AttendOutPlace.MidSta)  //中途站出勤的情况
                //{
                //    if (!road.is_bc_first && !road.is_bc_last)
                //    {
                //        if (Convert.ToInt32(firstT) % 2 == 1)  //基数趟车
                //            miles -= _downToChangedMiles;
                //        else
                //            miles -= _upToChangedMiles;
                //    }
                //}

                //if (road._OutPlace == AttendOutPlace.Garage && string.IsNullOrEmpty(road.BCBackGarageTrainID))  //夜班便乘回库的不算入段公里数
                //    miles += _inMiles;
                //else if (road._OutPlace == AttendOutPlace.MidSta)
                //{
                //    if (Convert.ToInt32(lastT) % 2 == 1)  //基数趟车
                //        miles -= _upToChangedMiles;
                //    else
                //        miles -= _downToChangedMiles;
                //}
            }
            else if (LineID == "2")
            {
                if (road._AttendPlace == AttendOutPlace.Garage && !road.is_bc_first && !road.is_bc_last)
                    miles += _outMiles;
                if (road._OutPlace == AttendOutPlace.Garage && string.IsNullOrEmpty(road.BCBackGarageTrainID))
                    miles += _inMiles;

                for (int i = 0; i < road.Items.Count; i++)
                {
                    Train train = road.Items[i] as Train;
                    AttendOutPlace start;
                    AttendOutPlace end;
                    if ((train.IsLastTrip && road._OutPlace == train.EndPlace) || i < road.Items.Count - 1 || road._ClassType == ClassType.Night)
                    {
                        end = train.EndPlace;
                    }
                    else
                    {
                        end = road._OutPlace;
                    }
                    if (i == 0 && road._ClassType != ClassType.Morning && !train.IsFirstOut)
                    {
                        start = road._AttendPlace;
                    }
                    else
                    {
                        start = train.StartPlace;
                    }
                    miles += getline2miles2(start, end);
                    //miles += getline2miles(train.StartPlace, train.EndPlace);
                    //if (train.IsLastTrip || i < road.Items.Count - 1 || road._ClassType == ClassType.Night)
                    //{
                    //    miles += getline2miles2(train.StartPlace, train.EndPlace);
                    //}
                    //else
                    //    miles += getline2miles2(train.StartPlace, road._OutPlace);
                    //miles += getline2miles(train.StartID, train.EndID);
                }

                //if (road._AttendPlace == AttendOutPlace.MidSta)
                //{
                //    if (!road.is_bc_first && !road.is_bc_last)
                //    {
                //        if (Convert.ToInt32(firstT) % 2 == 1)  //基数趟车
                //            miles -= _downToChangedMiles;
                //        else
                //        {
                //            if (road.GetFirstTrain().StartPlace == AttendOutPlace.STZSta)
                //                miles -= _upToChangedMiles;
                //            else
                //                miles -= _hKHUpToChangedMiles;
                //        }

                //    }
                //}

                //if (road._OutPlace == AttendOutPlace.MidSta)
                //{
                //    if (Convert.ToInt32(lastT) % 2 == 1)  //基数趟车
                //    {
                //        if (road.GetLastTrain().EndPlace == AttendOutPlace.STZSta)
                //            miles -= _upToChangedMiles;
                //        else
                //            miles -= _hKHUpToChangedMiles;
                //    }
                //    else
                //        miles -= _downToChangedMiles;
                //}
            }

            return miles.ToString();
        }


        public double getline2miles(AttendOutPlace startP, AttendOutPlace endP)
        {
            if (startP == AttendOutPlace.Garage || startP == AttendOutPlace.FirSta)
            {
                if (endP == AttendOutPlace.MidSta)
                    return _downToChangedMiles;
                else if (endP == AttendOutPlace.STZSta)
                    return _totalMiles;
                else if (endP == AttendOutPlace.LastSta)
                    return _hKHTotalMiles;
            }
            else if (startP == AttendOutPlace.STZSta)
            {
                if (endP == AttendOutPlace.Garage || endP == AttendOutPlace.FirSta)
                    return _totalMiles;
                if (endP == AttendOutPlace.MidSta)
                    return _upToChangedMiles;
            }
            else if (startP == AttendOutPlace.LastSta)
            {
                if (endP == AttendOutPlace.Garage || endP == AttendOutPlace.FirSta)
                    return _hKHTotalMiles;
                else if (endP == AttendOutPlace.MidSta)
                    return _hKHUpToChangedMiles;
            }

            return 0;
        }
        public double getline2miles2(AttendOutPlace startP, AttendOutPlace endP)
        {
            DataRow[] rows = Kilometersdt.Select("(StartStationID in " + GetPlace(startP) + " and EndStationID in " + GetPlace(endP) + ") or (StartStationID in " + GetPlace(endP) + " and EndStationID in " + GetPlace(startP) + ")");
            if (rows.Length > 0)
            {
                return double.Parse(rows[0]["Kilometers"].ToString());
            }
            else
            {
                return 0;
            }
        }
        public double getline2miles(int startID, int endID)
        {
            DataRow[] rows = Kilometersdt.Select("(StartStationID='" + startID + "' and EndStationID='" + endID + "') or (StartStationID='" + endID + "' and EndStationID='" + startID + "')");
            if (rows.Length > 0)
            {
                return double.Parse(rows[0]["Kilometers"].ToString());
            }
            else
            {
                return 0;
            }
            //if (startP == AttendOutPlace.Garage || startP == AttendOutPlace.FirSta)
            //{
            //    if (endP == AttendOutPlace.MidSta)
            //        return _downToChangedMiles;
            //    else if (endP == AttendOutPlace.STZSta)
            //        return _totalMiles;
            //    else if (endP == AttendOutPlace.LastSta)
            //        return _hKHTotalMiles;
            //}
            //else if (startP == AttendOutPlace.STZSta)
            //{
            //    if (endP == AttendOutPlace.Garage || endP == AttendOutPlace.FirSta)
            //        return _totalMiles;
            //    if (endP == AttendOutPlace.MidSta)
            //        return _upToChangedMiles;
            //}
            //else if (startP == AttendOutPlace.LastSta)
            //{
            //    if (endP == AttendOutPlace.Garage || endP == AttendOutPlace.FirSta)
            //        return _hKHTotalMiles;
            //    else if (endP == AttendOutPlace.MidSta)
            //        return _hKHUpToChangedMiles;
            //}

            //return 0;
        }
        public String GetPlace(AttendOutPlace place)
        {
            string result = "(";
            //if (place == AttendOutPlace.Garage)
            //{
            //    result = "车辆段";
            //}
            if (_lineID == "1")
            {
                if (place == AttendOutPlace.MidSta)
                    result += "'10'";
                else if (place == AttendOutPlace.LastSta)
                    result += "'22'";
                else if (place == AttendOutPlace.FirSta)
                    result += "'1'";
                else if (place == AttendOutPlace.Garage)
                    result += "'66','67'";

            }
            else if (_lineID == "2")
            {
                if (place == AttendOutPlace.MidSta)
                    result += "'10'";
                else if (place == AttendOutPlace.FirSta)
                    result += "'1'";
                else if (place == AttendOutPlace.LastSta)
                    result += "'26'";
                else if (place == AttendOutPlace.STZSta)
                    result += "'18'";
                else if (place == AttendOutPlace.HKHSta)
                    result += "'22'";
                else if (place == AttendOutPlace.ZYYSta)
                    result += "'15'";
                else if (place == AttendOutPlace.Garage)
                    result += "'66','67'";
            }
            result += ")";

            return result;
        }
        public string GetAttendOutPlace(AttendOutPlace place)
        {
            string result = "";
            if (place == AttendOutPlace.Garage)
            {
                result = "车辆段";
            }
            else if (_lineID == "1")
            {
                if (place == AttendOutPlace.MidSta)
                    result = "启工街站";
                else if (place == AttendOutPlace.LastSta)
                    result = "黎明广场站";
                else if (place == AttendOutPlace.FirSta)
                    result = "十三号街站";

            }
            else if (_lineID == "2")
            {
                if (place == AttendOutPlace.MidSta)
                    result = "青年大街站";
                else if (place == AttendOutPlace.FirSta)
                    result = "全运路站";
                else if (place == AttendOutPlace.LastSta)
                    result = "蒲田路站";
                else if (place == AttendOutPlace.STZSta)
                    result = "三台子站";
                else if (place == AttendOutPlace.HKHSta)
                    result = "航空航天大学站";
                else if (place == AttendOutPlace.ZYYSta)
                    result = "中医药大学站";
            }

            if (result == "")
            {
                string err = "";
            }

            return result;
        }

        /// <summary>
        /// 更新交路表集合的序号ZB，BB，YB，All
        /// </summary>
        /// <param name="cls">"ZB"，"BB"，"YB"，"All"</param>
        public void UpdateIndex(string cls)
        {
            if (cls == "ZB" || cls == "All")
            {
                //_crossingRoadZB.Sort();
                int index = 1;
                for (int i = 0; i < _crossingRoadZB.Count; i++)
                {
                    _crossingRoadZB[i].ID = (i + 1).ToString();
                    if (!string.IsNullOrEmpty(_crossingRoadZB[i].type.Trim()))
                    {
                        _crossingRoadZB[i].CrName = "早" + _crossingRoadZB[i].type;
                    }
                    else
                    {
                        _crossingRoadZB[i].CrName = "早" + index;
                        index++;
                    }
                }
            }
            if (cls == "BB" || cls == "All")
            {
                //_crossingRoadBB.Sort();
                int index = 1;
                for (int i = 0; i < _crossingRoadBB.Count; i++)
                {
                    _crossingRoadBB[i].ID = (i + 1).ToString();
                    if (!string.IsNullOrEmpty(_crossingRoadBB[i].type.Trim()))
                    {
                        _crossingRoadBB[i].CrName = "白" + _crossingRoadBB[i].type;
                    }
                    else
                    {
                        _crossingRoadBB[i].CrName = "白" + index;
                        index++;
                    }
                }
            }
            if (cls == "YB" || cls == "All")
            {
                //_crossingRoadYB.Sort();
                int index = 1;
                for (int i = 0; i < _crossingRoadYB.Count; i++)
                {
                    _crossingRoadYB[i].ID = (i + 1).ToString();
                    if (!string.IsNullOrEmpty(_crossingRoadYB[i].type.Trim()))
                    {
                        _crossingRoadYB[i].CrName = "晚" + _crossingRoadYB[i].type;
                    }
                    else
                    {
                        _crossingRoadYB[i].CrName = "晚" + index;
                        index++;
                    }

                }
            }

        }

        /*****************************************************************************************/

        private bool CanGenerate()
        {
            return _crossingRoadView.CheckBianCTrain() && this.IsValidate() && _crossingRoadView.CheckTableNameSelected() && !_isExporting;
        }

        private bool CheckEarlyBackGarageCollection()
        {
            bool result = true;

            foreach (EarlyBackGarageModel item in EarlyBackGarageCollections)
            {
                if (!string.IsNullOrEmpty(item.TrainID)) //如果车次不为空，则地点和人数都不能为空
                {
                    if (string.IsNullOrEmpty(item.StationSelected.StationName))
                    {
                        MessageBoxHelper.ShowError("请输入提前便乘回库的地点！");
                        result = false;

                        break;
                    }
                    else if (!GlobalVariables.IsNumberic(item.Num.ToString()))
                    {
                        MessageBoxHelper.ShowError("提前便乘回库人数处请输入数字！");
                        result = false;

                        break;
                    }
                    else if (item.Num < 1)
                    {
                        MessageBoxHelper.ShowError("提前便乘回库人数至少为1个！");
                        result = false;

                        break;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 检查白班便乘出勤的车次是否存在
        /// </summary>
        /// <returns></returns>
        private bool CheckTrainIDExists(string TrainID)
        {
            return _crossingRoadAccess.CheckTrainIDExists(TimeTable.Name, TrainID);
        }

        private bool CheckUnMorningBcCollection()
        {
            foreach (UnMoringBCModel model in UnMorningBCCollections)
            {
                if (!string.IsNullOrEmpty(model.TrainID))
                {
                    if (!rx.IsMatch(model.TrainID) || model.TrainID.Length != 5)
                    {
                        MessageBoxHelper.ShowError("白/夜班便乘出勤处请选择正确格式的车次号！");
                        return false;
                    }
                    else if (string.IsNullOrEmpty(model.SelectedClass))
                    {
                        MessageBoxHelper.ShowError("白/夜班便乘出勤处请选择车次对应的班次！");
                        return false;
                    }
                    else if (!CheckTrainIDExists(model.TrainID))
                    {
                        MessageBoxHelper.ShowError(string.Format("白/夜班便乘出勤车次 {0} 不存在于时刻表 {1} 中，请确认后重新输入", model.TrainID, TimeTable.Name));
                        return false;
                    }
                }
            }

            return true;
        }

        private void SaveParametersMethod()
        {
            try
            {
                //PhoneOutTrain--
                CrossingRoadParameter parameters = new CrossingRoadParameter();
                InitParameters(ref parameters);
                _crossingRoadAccess.SaveCrossingRoadParameters(parameters);
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError("保存交路参数失败");
#if DEBUG
                MessageBoxHelper.ShowError(ex);
#endif

            }
        }
        private string ValidateCrossingRoad()
        {
            //bool result = false ;
            string msg = null;
            List<int> trainIdList = new List<int>();
            Dictionary<int, CrossingRoadObject> crossingroadDic = new Dictionary<int, CrossingRoadObject>();

            //检测是否重复
            foreach (var classItem in classList)
            {
                foreach (var item in classItem)
                {
                    if (string.IsNullOrEmpty(item.StringCrossingRoad))
                        continue;
                    var trains = Regex.Matches(item.StringCrossingRoad, "[0-9]{5}", RegexOptions.IgnoreCase);
                    for (int i = 0; i < trains.Count; i++)
                    {
                        var strTrain = trains[i];
                        int trainId = Convert.ToInt32(strTrain.Value);
                        if (trainIdList.Contains(trainId))
                        {
                            //判断是不是接班车，如果不是则表示有重复车次
                            CrossingRoadObject crossingroad = crossingroadDic[trainId];
                            string classString1 = string.Empty, classString2 = string.Empty;
                            if (_crossingRoadZB.Contains(crossingroadDic[trainId]))
                                classString1 = "早班";
                            else if (_crossingRoadBB.Contains(crossingroadDic[trainId]))
                                classString1 = "白班";
                            else if (_crossingRoadYB.Contains(crossingroadDic[trainId]))
                                classString1 = "夜班";
                            if (_crossingRoadZB.Contains(item))
                                classString2 = "早班";
                            else if (_crossingRoadBB.Contains(item))
                                classString2 = "白班";
                            else if (_crossingRoadYB.Contains(item))
                                classString2 = "夜班";
                            if (i == 0)
                            {
                                //if ((LineID == "1" && strTrain.Value.Substring(3, 2) == "'02") || (LineID == "2" && strTrain.Value.Substring(3, 2) == "01"))

                                //{

                                //    MessageBoxHelper.ShowError("车次" + trainId + "重复，在交路"+classString1 + crossingroadDic[trainId].ID+"和"+classString2+item.ID + "，保存失败，请检查");
                                //    result = false;
                                //    return result;
                                //}
                            }
                            else
                            {
                                //MessageBoxHelper.ShowError("车次" + trainId + "重复，在交路" + classString1 + crossingroadDic[trainId].ID + "和" + classString2 + item.ID + "，保存失败，请检查");
                                //result = false;
                                //return result;
                                msg += "车次" + trainId + "重复，在交路" + classString1 + crossingroadDic[trainId].ID + "和" + classString2 + item.ID + ";\n";
                            }
                            //crossingroad.AttenPlace
                        }
                        else
                        {
                            trainIdList.Add(trainId);
                            crossingroadDic.Add(trainId, item);
                        }

                    }
                }
            }
            //检测是否有未使用车次
            string unUsertrainList = "";
            foreach (var item in TrainList)
            {
                int trainid = Convert.ToInt32(item.TrainID);
                if (!trainIdList.Contains(trainid))
                {
                    //MessageBoxHelper.ShowError("车次" + trainid + "未使用过，保存失败，请检查");
                    //result = false;
                    //return result;
                    unUsertrainList += trainid + "、";
                    //return "车次" + unUsertrainList + "未使用过，确定要保存吗？";
                }
            }

            if (unUsertrainList != "")
            {

                unUsertrainList = unUsertrainList.Substring(0, unUsertrainList.Length - 1);
                msg += "车次" + unUsertrainList + "未使用过;\n";
            }
            if(!String.IsNullOrEmpty(msg))
                msg += "确定要保存吗？";
            return msg;
        }
        private void GenerateCrossingRoadMethod()
        {
            try
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("生成交路");
                if (!CheckEarlyBackGarageCollection() || !CheckUnMorningBcCollection())
                {
                    return;
                }

                CrossingRoadParameter parameters = new CrossingRoadParameter();
                InitParameters(ref parameters);

                //generateCrossingRoad = new GenerateCrossingRoad(parameters);

                generateCrossingRoadByBCNum = new GenerateCrossingRoadByBCNum(ref parameters);

                GenerateCrossingRoadResultType result = generateCrossingRoadByBCNum.Generate2();

                if (result == GenerateCrossingRoadResultType.Success)
                    InitCrossingRoadObjects();
                else
                    MessageBoxHelper.ShowError(GetGenerateCrossingRoadResultContent.GetResultContent(result));
            }
            catch (Exception ex)
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
            }
        }
        private int GetInt(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return 0;
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        public CrossingRoadParameter LoadParameters(string name)
        {
            CrossingRoadParameter parameters = null;
            DataTable dtParameters = _crossingRoadAccess.GetCrossingRoadParameters(name, LineID);

            if (dtParameters != null && dtParameters.Rows.Count > 0)
            {
                DataTable dtParamSub = _crossingRoadAccess.GetCrossingRoadParamSub(dtParameters.Rows[0]["id"].ToString());

                parameters = new CrossingRoadParameter();

                parameters.bc_last_arr = new ArrayList();
                parameters.bc_first_arr = new ArrayList();
                parameters.UnMorningBcCollection = new Dictionary<string, ClassType>();
                parameters.UnNightBCOutCollection = new ArrayList();
                parameters.EarlyBackGarageCollections = new ObservableCollection<EarlyBackGarageModel>();
                parameters.PhoneAttendOutCollections = new ObservableCollection<TrainIdModel>();

                int perMin = 60;
                DataRow row = dtParameters.Rows[0];
                parameters.lineID = LineID;
                parameters.PhoneOutTrain = row["crp_phone_outoff_train"].ToString();
                parameters.NightEmptyTrain = row["crp_night_empty_train"].ToString();
                parameters.lunchCrossRoadCount = GetInt(row["crp_lunch_numberof_dingfanquan"]);
                parameters.supperCrossRoadCount = GetInt(row["crp_dinner_numberof_dingfanquan"]);
                parameters.Is_NightMeal_BC = Convert.ToBoolean(row["crp_is_biancheng"]);
                parameters.int_ChangeTime_ZB = GetInt(row["crp_zb_exchange_time"]);
                parameters.int_ChangeTime_BB = GetInt(row["crp_bb_exchange_time"]);
                parameters.int_ZB_OutTime = GetInt(row["crp_zb_out_time"]);
                parameters.int_ZB_BackTime = GetInt(row["crp_zb_back_time"]);
                parameters.int_BB_OutTime = GetInt(row["crp_bb_out_time"]);
                parameters.int_LunchTime = GetInt(row["crp_lunch_time"]);
                parameters.int_SuperTime = GetInt(row["crp_dinner_time"]);
                parameters.restTime = GetInt(row["crp_normal_exchange_time"]) / perMin;
                parameters.mealRestTime = GetInt(row["crp_after_meel_time"]) / perMin;
                parameters.GarageAhead = GetInt(row["crp_cld_atten_advance"]) / perMin;
                parameters.GarageBCAhead = GetInt(row["crp_cld_biancheng_advance"]) / perMin;
                parameters.NormalAhead = GetInt(row["crp_zx_atten_advance"]) / perMin;
                parameters.NormalDelay = GetInt(row["crp_normal_delay"]) / perMin;
                parameters.GarageDelay = GetInt(row["crp_garage_delay"]) / perMin;
                parameters.BcGarageDelay = GetInt(row["crp_bc_garage_delay"]) / perMin;


                DataRow[] bcFirstRows = dtParamSub.Select("crpo_tag='" + ParametersSubType.bc_first.ToString() + "'");
                for (int i = 0; i < bcFirstRows.Length; i++)
                {
                    parameters.bc_first_arr.Add(bcFirstRows[i]["crpo_train"]);
                }

                DataRow[] bcLastRows = dtParamSub.Select("crpo_tag='" + ParametersSubType.bc_last.ToString() + "'");
                for (int i = 0; i < bcLastRows.Length; i++)
                {
                    parameters.bc_last_arr.Add(bcLastRows[i]["crpo_train"]);
                }

                DataRow[] unmorningRows = dtParamSub.Select("crpo_tag='" + ParametersSubType.unmorning_bc.ToString() + "'");
                for (int i = 0; i < unmorningRows.Length; i++)
                {

                    if (unmorningRows[i]["crpo_class"].ToString() == "白班")
                        parameters.UnMorningBcCollection.Add(unmorningRows[i]["crpo_train"].ToString(), ClassType.Day);
                    else if (unmorningRows[i]["crpo_class"].ToString() == "夜班")
                        parameters.UnMorningBcCollection.Add(unmorningRows[i]["crpo_train"].ToString(), ClassType.Night);
                    else
                        continue;
                }
                DataRow[] unnightRows = dtParamSub.Select("crpo_tag='" + ParametersSubType.unnight_bc_out.ToString() + "'");
                for (int i = 0; i < unnightRows.Length; i++)
                {
                    parameters.UnNightBCOutCollection.Add(unnightRows[i]["crpo_train"]);
                }

                DataRow[] earlyBackRows = dtParamSub.Select("crpo_tag='" + ParametersSubType.early_back_garage.ToString() + "'");
                for (int i = 0; i < earlyBackRows.Length; i++)
                {
                    if (string.IsNullOrEmpty(earlyBackRows[0]["crpo_train"].ToString()))
                        continue;

                    EarlyBackGarageModel model = new EarlyBackGarageModel()
                    {
                        TrainID = earlyBackRows[i]["crpo_train"].ToString(),
                        StationSelected = new StationToEnum() { StationName = earlyBackRows[i]["crpo_station"].ToString() },
                        Num = Convert.ToInt32(earlyBackRows[i]["crpo_number"])
                    };
                    parameters.EarlyBackGarageCollections.Add(model);
                }

                DataRow[] mealCrossRoadRows = dtParamSub.Select("crpo_tag='" + ParametersSubType.meal_cross_road.ToString() + "'");
                for (int i = 0; i < mealCrossRoadRows.Length; i++)
                {
                    SetMealCrossRoadModel model = new SetMealCrossRoadModel();
                    model.MealTime = mealCrossRoadRows[i]["crpo_class"].ToString();
                    if (model.MealTime == "午饭")
                    {
                        model.Is_Continue_Enabled = false;
                        model.Is_BC_Enabled = false;
                    }

                    model.Is_NightMeal_BC = Convert.ToBoolean(mealCrossRoadRows[i]["crpo_is_biancheng"]);
                    model.Is_Continue = Convert.ToBoolean(mealCrossRoadRows[i]["crpo_is_continuous_duty"]);
                    parameters.SetMealCrossRoadCollection.Add(model);
                }
            }

            return parameters;
        }

        private void InitParameters(ref CrossingRoadParameter parameters)
        {
            try
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("初始化交路信息");
                parameters.lineID = _lineID;

                parameters.TableID = Convert.ToInt32(TimeTable.ID);

                parameters.TableName = TimeTable.Name;

                parameters.FirstID = FirstRoundID;

                parameters.PhoneOutTrain = PhoneOutTrain;

                parameters.lunchCrossRoadCount = Convert.ToInt32(LunchCrossRoadCount);

                parameters.supperCrossRoadCount = Convert.ToInt32(SupperCrossRoadCount);

                parameters.Is_NightMeal_BC = Is_NightMeal_BC;

                parameters.NightEmptyTrain = NightEmptyTrain;

                parameters.int_ChangeTime_ZB = (int)_crossingRoadView.stp_zb.GetTimeSecond();

                parameters.int_ChangeTime_BB = (int)_crossingRoadView.stp_by.GetTimeSecond();

                parameters.int_ZB_OutTime = (int)_crossingRoadView.stp_outZB.GetTimeSecond();

                parameters.int_ZB_BackTime = (int)_crossingRoadView.stp_backZB.GetTimeSecond();

                parameters.int_BB_OutTime = (int)_crossingRoadView.stp_outBB.GetTimeSecond();

                parameters.int_LunchTime = (int)_crossingRoadView.lunch_time.GetTimeSecond();

                parameters.int_SuperTime = (int)_crossingRoadView.dinner_time.GetTimeSecond();

                parameters.restTime = Convert.ToInt32(this.RestTime) * 60;

                parameters.mealRestTime = Convert.ToInt32(this.MealRestTime) * 60;

                parameters.GarageAhead = Convert.ToInt32(this.GarageAhead) * 60;

                parameters.GarageBCAhead = Convert.ToInt32(this.GarageBCAhead) * 60;

                parameters.NormalAhead = Convert.ToInt32(this.NormalAhead) * 60;

                parameters.NormalDelay = Convert.ToInt32(this.NormalDelay) * 60;

                parameters.GarageDelay = Convert.ToInt32(this.GarageDelay) * 60;

                parameters.BcGarageDelay = Convert.ToInt32(this.BcGarageDelay) * 60;

                parameters.bc_last_arr = new ArrayList();

                for (int i = 0; i < _crossingRoadView.BianCArray_Last.Count; i++)
                {
                    if (_crossingRoadView.BianCArray_Last[i].SelectedItem == null || string.IsNullOrEmpty(_crossingRoadView.BianCArray_Last[i].SelectedItem.ToString()))
                        continue;
                    parameters.bc_last_arr.Add(_crossingRoadView.BianCArray_Last[i].SelectedItem.ToString());
                }

                parameters.bc_first_arr = new ArrayList();

                for (int j = 0; j < _crossingRoadView.BianCArray_First.Count; j++)
                {
                    if (_crossingRoadView.BianCArray_First[j].SelectedItem == null || string.IsNullOrEmpty(_crossingRoadView.BianCArray_First[j].SelectedItem.ToString()))
                        continue;
                    parameters.bc_first_arr.Add(_crossingRoadView.BianCArray_First[j].SelectedItem.ToString());
                }

                foreach (EarlyBackGarageModel earlybackItem in EarlyBackGarageCollections)
                {
                    if (string.IsNullOrEmpty(earlybackItem.TrainID))
                        continue;

                    EarlyBackGarageModel model = new EarlyBackGarageModel()
                    {
                        TrainID = earlybackItem.TrainID,
                        StationSelected = earlybackItem.StationSelected,
                        Num = earlybackItem.Num
                    };

                    parameters.EarlyBackGarageCollections.Add(model);
                }

                foreach (UnMoringBCModel unMorningModel in UnMorningBCCollections)
                {
                    if (string.IsNullOrEmpty(unMorningModel.TrainID))
                        continue;

                    if (unMorningModel.SelectedClass == "白班")
                        parameters.UnMorningBcCollection.Add(unMorningModel.TrainID, ClassType.Day);
                    else if (unMorningModel.SelectedClass == "夜班")
                        parameters.UnMorningBcCollection.Add(unMorningModel.TrainID, ClassType.Night);
                    else
                        continue;
                }

                parameters.UnNightBCOutCollection = new ArrayList();
                foreach (UnNightBCOutModel unNightBcOutModel in UnNightBC_OutCollections)
                {
                    if (string.IsNullOrEmpty(unNightBcOutModel.TrainID))
                        continue;

                    parameters.UnNightBCOutCollection.Add(unNightBcOutModel.TrainID);
                }

                parameters.UnplanCollection = UnplanCollections;


                foreach (SetMealCrossRoadModel setMealCrossRoadModel in SetMealCrossRoalCollections)
                {
                    if (string.IsNullOrEmpty(setMealCrossRoadModel.MealTime))
                        continue;

                    setMealCrossRoadModel.IsUsed = false;
                    parameters.SetMealCrossRoadCollection.Add(setMealCrossRoadModel);
                }

                foreach (TrainIdModel train in PhoneAttendOutCollections)
                {
                    if (train==null||string.IsNullOrEmpty(train.TrainId))
                        continue;

                    parameters.PhoneAttendOutCollections.Add(train);
                }

                parameters.BcUpNum = parameters.bc_first_arr.Count;

                parameters.BcDownNum = parameters.bc_last_arr.Count;
            }
            catch (Exception ex)
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
            }

        }

        private bool IsValidate()
        {
            return string.IsNullOrEmpty(ValidateTime("RestTime")) && string.IsNullOrEmpty(ValidateTime("MealRestTime")) &&
                string.IsNullOrEmpty(ValidateTime("LunchCrossRoadCount")) && string.IsNullOrEmpty(ValidateTime("SupperCrossRoadCount")) &&
                string.IsNullOrEmpty(ValidateTime("GarageAhead")) && string.IsNullOrEmpty(ValidateTime("GarageBCAhead")) && string.IsNullOrEmpty(ValidateTime("NormalAhead"));
        }

        private string ValidateTime(string columnName)
        {
            string error = null;
            switch (columnName)
            {
                case "LunchCrossRoadCount":
                    if (!rx.IsMatch(this.LunchCrossRoadCount))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.LunchCrossRoadCount) > 5)
                    {
                        error = "设置的顶饭圈人数过多！";
                    }
                    break;
                case "SupperCrossRoadCount":
                    if (!rx.IsMatch(this.SupperCrossRoadCount))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.SupperCrossRoadCount) > 5)
                    {
                        error = "设置的顶饭圈人数过多！";
                    }
                    break;
                case "RestTime":
                    if (!rx.IsMatch(this.RestTime))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.RestTime) > 60)
                    {
                        error = "设置的休息时间过长！";
                    }
                    break;
                case "MealRestTime":
                    if (!rx.IsMatch(this.MealRestTime))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.MealRestTime) > 90)
                    {
                        error = "设置的休息时间过长！";
                    }
                    break;
                case "GarageAhead":
                    if (!rx.IsMatch(this.GarageAhead))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.GarageAhead) > 90)
                    {
                        error = "车辆段出勤提前时间过早！";
                    }
                    break;
                case "GarageBCAhead":
                    if (!rx.IsMatch(this.GarageBCAhead))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.GarageBCAhead) > 90)
                    {
                        error = "车辆段便乘出勤提前时间过早！";
                    }
                    break;
                case "NormalAhead":
                    if (!rx.IsMatch(this.NormalAhead))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.NormalAhead) > 90)
                    {
                        error = "正线出勤提前时间过早！";
                    }
                    break;
                case "NormalDelay":
                    if (!rx.IsMatch(this.NormalDelay))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.NormalDelay) > 90)
                    {
                        error = "正线退勤延迟时间过大！";
                    }
                    break;
                case "GarageDelay":
                    if (!rx.IsMatch(this.GarageDelay))
                    {
                        error = "请输入数字！";
                    }
                    else if (Convert.ToInt32(this.GarageDelay) > 90)
                    {
                        error = "车辆段退勤延迟时间过大！";
                    }
                    break;
            }

            return error;
        }

        /// <summary>
        /// 初始化车次列表
        /// </summary>
        /// <param name="changeZb">早白班交接班时间</param>
        /// <param name="changeBy">白班夜班交接班时间</param>
        public void InitTrainList(string changeZb, string changeBy)
        {
            if (null != ZBTrainList)
                ZBTrainList.Clear();

            ZBTrainList = _crossingRoadAccess.GetMorningShiftTrain(FirstRoundID, changeZb, TimeTable.Name);

            if (null != TrainList)
                TrainList.Clear();

            TrainList = _crossingRoadAccess.GetAllTrain(TimeTable.ID, TimeTable.Name);
            TrainDictionary.Clear();
            foreach (var item in TrainList)
            {
                TrainDictionary.Add(item.TrainID, item);
            }

            if (null != NightBackTrains)
                NightBackTrains.Clear();
            if (null != EarlyBackGarageCollections)
                EarlyBackGarageCollections.Clear();
            if (null != BBFirstOutTrains)
            {
                BBFirstOutTrains.Clear();
                PhoneOutTrain = null;
            }

            NightBackTrains = _crossingRoadAccess.GetNightBackTrain(changeBy, TimeTable.Name);

            BBFirstOutTrains = _crossingRoadAccess.GetBBFirstOutTrains(changeZb, (int)_crossingRoadView.stp_outBB.GetTimeSecond(), FirstRoundID, TimeTable.Name);
            //DayTrainsCollections = _crossingRoadAccess.GetDayTrains(changeZb,changeBy,TimeTable.Name);
        }

        /************************************************************非夜班便乘退勤的车次选择逻辑
         */
        private void Add_UnNightBC_Out_Command_Method()
        {
            if (string.IsNullOrEmpty(TimeTable.Name))
            {
                MessageBoxHelper.ShowError("请先选择时刻表");
                return;
            }
            if (UnNightBC_OutCollections.Count >= Max_UnMornigBcNum)
            {
                MessageBoxHelper.ShowTips(string.Format("当前仅支持最多{0}组便乘退勤，如有需要，请与开发人员联系！", Max_UnMornigBcNum));
                return;
            }

            UnNightBCOutModel item = new UnNightBCOutModel();
            this.UnNightBC_OutCollections.Add(item);
        }
        private void Add_UnplanCommand_method()
        {
            if (string.IsNullOrEmpty(TimeTable.Name))
            {
                MessageBoxHelper.ShowError("请先选择时刻表");
                return;
            }
            if (UnplanCollections.Count >= 7)
            {
                MessageBoxHelper.ShowTips(string.Format("当前不参与安排车次最多支持{0}组，如有需要，请与开发人员联系！", MAX_PhoneAttendOutMaxNum));
                return;
            }

            this.UnplanCollections.Add(new TrainIdModel());
        }
        /// <summary>
        /// 电话退勤
        /// </summary>
        private void Add_PhoneAttendOutCommand_method()
        {
            if (string.IsNullOrEmpty(TimeTable.Name))
            {
                MessageBoxHelper.ShowError("请先选择时刻表");
                return;
            }
            if (PhoneAttendOutCollections.Count >= MAX_PhoneAttendOutMaxNum)
            {
                MessageBoxHelper.ShowTips(string.Format("当前电话退勤最多支持{0}组，如有需要，请与开发人员联系！", MAX_PhoneAttendOutMaxNum));
                return;
            }

            this.PhoneAttendOutCollections.Add(new TrainIdModel());
        }
        /************************************************************非夜班便乘退勤的车次选择逻辑
         */

        /************************************************************提前便乘回库的车次选择逻辑
         */
        private void Add_UnMorningBC_Command_Method()
        {
            if (string.IsNullOrEmpty(TimeTable.Name))
            {
                MessageBoxHelper.ShowError("请先选择时刻表");
                return;
            }
            if (UnMorningBCCollections.Count >= Max_UnMornigBcNum)
            {
                MessageBoxHelper.ShowTips(string.Format("当前白/夜班出勤便乘最多支持{0}组，如有需要，请与开发人员联系！", Max_UnMornigBcNum));
                return;
            }

            UnMoringBCModel item = new UnMoringBCModel();
            this.UnMorningBCCollections.Add(item);
        }


        private void Add_EarlyBackGarageCommand_Method()
        {
            if (string.IsNullOrEmpty(TimeTable.Name))
            {
                MessageBoxHelper.ShowError("请先选择时刻表");
                return;
            }
            //if (EarlyBackGarageCollections.Count >= Max_EarlyBackNum)
            //{
            //    MessageBoxHelper.ShowTips(string.Format("当前仅支持最多{0}组提前便乘，如有需要，请与开发人员联系！", Max_EarlyBackNum));
            //    return;
            //}

            EarlyBackGarageModel item = new EarlyBackGarageModel();
            item.NightBackTrainCollections = this.NightBackTrains;

            this.EarlyBackGarageCollections.Add(item);
        }

        private void SetMealCommand_Method()
        {
            if (string.IsNullOrEmpty(TimeTable.Name))
            {
                MessageBoxHelper.ShowError("请先选择时刻表");
                return;
            }

            if (SetMealCrossRoalCollections.Count >= Max_SetMealNum)
            {
                MessageBoxHelper.ShowTips(string.Format("当前仅支持最多{0}组顶饭圈交路，如有需要，请与开发人员联系！", Max_SetMealNum));
                return;
            }

            SetMealCrossRoadModel item = new SetMealCrossRoadModel();

            this.SetMealCrossRoalCollections.Add(item);

        }

        private bool CanAdd_EarlyBackGarage()
        {
            return true;
        }

        private bool CanSetMealCommand()
        {
            return true;
        }

        /************************************************************提前便乘回库的车次选择逻辑
         */

        /**********************************************************************增加默认交路的逻辑
         */
        private void AddDefaultRoadsCommand_Method()
        {
            try
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("添加非默认交路");
                string attenT = "00:00:00";
                string offT = "00:00:00";

                string offT_RB = "00:00:00";

                string zhengxian = string.Empty;
                if (LineID == "1")
                    zhengxian = "启工街站";
                else
                    zhengxian = "青年大街站";

                //*************早班
                AddRow("ZB", GetNewCrossRoad("调车", "03:50:00", "车辆段", "08:30:00", "车辆段")); //调车
                AddRow("ZB", GetNewCrossRoad("试车线", "03:50:00", "车辆段", "08:30:00", "车辆段")); //试车线
                //早备班出勤时间、退勤时间
                attenT = _crossingRoadZB[0].PlanTime;
                offT = GetFirstOffTime(_crossingRoadZB);
                AddRow("ZB", GetNewCrossRoad("备班", attenT, "车辆段", offT, "车辆段")); //早备班
                AddRow("ZB", GetNewCrossRoad("月备班", attenT, "车辆段", offT, "车辆段")); //早月备班
                //热备
                offT_RB = GetFirstTrainToFirstSta(_crossingRoadBB);  //白1首次到达十三号街的时间
                AddRow("ZB", GetNewCrossRoad("热备", attenT, "车辆段", offT_RB, "车辆段")); //早热备
                

                //司机长


                AddRow("ZB", GetNewCrossRoad("司机长", "05:00:00", "车辆段", "08:30:00", zhengxian)); //试车线

                AddRow("ZB", GetNewCrossRoad("督导员", "05:00:00", "车辆段", "08:30:00", zhengxian)); //试车线

                //************白班
                AddRow("BB", GetNewCrossRoad("调车", "08:30:00", "车辆段", "17:30:00", "车辆段")); //调车
                AddRow("BB", GetNewCrossRoad("试车线", "08:30:00", "车辆段", "17:30:00", "车辆段")); //试车线
                //白备班出勤时间、退勤时间
                attenT = _crossingRoadBB[0].PlanTime;
                offT = GetFirstOffTime(_crossingRoadBB);
                AddRow("BB", GetNewCrossRoad("备班", attenT, "车辆段", offT, "车辆段")); //白备班
                AddRow("BB", GetNewCrossRoad("月备班", attenT, "车辆段", offT, "车辆段")); //白月备班
                //热备
                attenT = GlobalVariables.FormatTime((GlobalVariables.FormatTimeToInt(offT_RB) - 15 * 60).ToString());
                offT_RB = GetFirstTrainToFirstSta(_crossingRoadYB);  //晚1首次到达十三号街的时间
                AddRow("BB", GetNewCrossRoad("热备", attenT, "车辆段", offT_RB, "车辆段")); //白热备

                //司机长
                AddRow("BB", GetNewCrossRoad("司机长", "08:00:00", zhengxian, "15:30:00", zhengxian)); //试车线
                AddRow("BB", GetNewCrossRoad("督导员", "08:00:00", zhengxian, "15:30:00", zhengxian)); //试车线

                //***********夜班
                AddRow("YB", GetNewCrossRoad("调车", "17:30:00", "车辆段", "22:00:00", "车辆段")); //调车
                AddRow("YB", GetNewCrossRoad("试车线", "17:30:00", "车辆段", "22:00:00", "车辆段")); //试车线
                //热备
                attenT = GlobalVariables.FormatTime((GlobalVariables.FormatTimeToInt(offT_RB) - 15 * 60).ToString());
                offT_RB = GetLastTrainTime(_crossingRoadYB);  //晚1首次到达十三号街的时间
                AddRow("YB", GetNewCrossRoad("热备", attenT, "车辆段", offT_RB, "车辆段")); //晚热备


                //晚备班出勤时间、退勤时间
                attenT = _crossingRoadYB[0].PlanTime;
                offT = "22:00:00";
                AddRow("YB", GetNewCrossRoad("备班", attenT, "车辆段", offT, "车辆段")); //备班
                AddRow("YB", GetNewCrossRoad("月备班", attenT, "车辆段", offT, "车辆段")); //月备班

                //司机长
                AddRow("YB", GetNewCrossRoad("司机长", "15:30:00", zhengxian, "23:00:00", "车辆段")); //试车线
                AddRow("YB", GetNewCrossRoad("督导员", "15:30:00", zhengxian, "23:00:00", "车辆段")); //试车线
                _crossingRoadZB.ZBSort();
                _crossingRoadBB.Sort();
                _crossingRoadYB.Sort();
                UpdateIndex("All");
            }
            catch (Exception ex)
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
            }
        }

        private bool Can_AddDefaultRoadsCommand_Method()
        {
            return _crossingRoadZB.Count > 0 && _crossingRoadBB.Count > 0 && _crossingRoadYB.Count > 0;
        }

        /// <summary>
        /// 获取第一个退勤的时间
        /// </summary>
        /// <param name="crossingRoadObjects"></param>
        /// <returns></returns>
        private string GetFirstOffTime(CrossingRoadObjects crossingRoadObjects)
        {
            string result = "24:59:59";

            for (int i = 0; i < crossingRoadObjects.Count; i++)
            {
                if (crossingRoadObjects[i].type == "" && crossingRoadObjects[i].OffTime.CompareTo(result) < 0)
                    result = crossingRoadObjects[i].OffTime;
            }

            return result;
        }
        public List<String> InitVersion()
        {
            List<String> versionList = new List<String>();
            versionList.Add("正式版");
            versionList.AddRange(_crossingRoadAccess.GetDraftNameList(TimeTable.ID));
            versionList.Add("新草稿");
            return versionList;
        }

        private string GetFirstTrainToFirstSta(CrossingRoadObjects crossingRoadObjects)
        {
            string result = "00:00:00";
            string stringTrainList = "";
            string[] TrainArr;

            for (int i = 0; i < crossingRoadObjects.Count; i++)
            {
                if (crossingRoadObjects[i].type != "")
                    continue;
                else
                {
                    stringTrainList = crossingRoadObjects[i].StringCrossingRoad;
                    TrainArr = stringTrainList.Split(new string[] { "--->" }, StringSplitOptions.None);
                    string train = "";
                    if (LineID == "1")//1号线
                    {
                        for (int n = 0; n < TrainArr.Length; n++)
                        {
                            train = TrainArr[n].Substring(0, 5);
                            if (Convert.ToInt32(train) % 2 == 1)
                            {
                                result = TrainArr[n].Substring(TrainArr[n].IndexOf(',') + 1, 8);
                                return result;
                            }
                            else
                                continue;
                        }
                    }
                    else //二号线
                    {
                        for (int k = 0; k < TrainArr.Length; k++)
                        {
                            train = TrainArr[k].Substring(0, 5);
                            if (Convert.ToInt32(train) % 2 == 0)
                            {
                                result = TrainArr[k].Substring(TrainArr[k].IndexOf(',') + 1, 8);
                                return result;
                            }
                            else
                                continue;
                        }
                    }
                }
            }
            return result;
        }

        private string GetLastTrainTime(CrossingRoadObjects crossingRoadObjects)
        {
            string result = "00:00:00";

            for (int i = 0; i < crossingRoadObjects.Count; i++)
            {
                if (crossingRoadObjects[i].type == "" && crossingRoadObjects[i].OffTime.CompareTo(result) > 0)
                    result = crossingRoadObjects[i].OffTime;
            }

            return result;
        }

        /// <summary>
        /// 通过指定参数获取新的一个交路，用于添加默认交路
        /// </summary>
        /// <param name="type">交路类型</param>
        /// <param name="attendT">出勤时间：hh：mm：ss</param>
        /// <param name="attendPlace">出勤地点</param>
        /// <param name="offT">退勤时间：hh：mm：ss</param>
        /// <param name="offPlace">退勤地点</param>
        /// <returns></returns>
        private CrossingRoadObject GetNewCrossRoad(string type, string attendT, string attendPlace, string offT, string offPlace)
        {
            CrossingRoadModel newRoadModel = CrossingRoadModel.CreateCrossingRoadModel();
            newRoadModel.type = type;

            newRoadModel.TrainTime = newRoadModel.PlanTime = attendT;
            newRoadModel.OffTime = offT;

            newRoadModel.AttenPlace = attendPlace;
            newRoadModel.OffPlace = offPlace;

            try
            {
                newRoadModel.Whours = Math.Round((double)(Math.Abs(GlobalVariables.FormatTimeToInt(offT) - GlobalVariables.FormatTimeToInt(attendT))) / 3600, 2).ToString();
            }
            catch (System.Exception ex)
            {
                newRoadModel.Whours = "0";
            }
            newRoadModel.Miles = "0";

            return new CrossingRoadObject(newRoadModel);
        }


        /**********************************************************************增加默认交路的逻辑
         */

        private void SaveAs()
        {
            try
            {
                //if (!ValidateCrossingRoad())
                //{
                //    return;
                //}
                string msg = ValidateCrossingRoad();
                if (!string.IsNullOrEmpty(msg))
                {
                    if (!MessageBoxHelper.ConfirmYesNo(msg))
                        return;
                }
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("保存交路");
                CheckIsCrossingRoadIn();
                if (_isCrossRoadIn)
                {
                    if (!MessageBoxHelper.ConfirmYesNo("该时刻表已生成出勤表，是否删除先前记录？"))
                        return;

                    if (!_crossingRoadAccess.DeleCrossingRoad(TimeTable.ID))
                    {
                        MessageBoxHelper.ShowError("保存失败！执行保存操作时异常！");
                        return;
                    }
                }

                DataTable dt = GetSaveTable(null);
                if (null == dt || dt.Rows.Count < 1)
                {
                    MessageBoxHelper.ShowError("未能保存空数据集！");
                    return;
                }
                if (_crossingRoadAccess.SaveNewCrossingRoad(dt, null))
                    MessageBoxHelper.ShowTips("保存交路表成功！");
                else
                    MessageBoxHelper.ShowTips("保存交路表失败！");

                //SaveTimeConfig();
                SaveParametersMethod();

                _isCrossRoadIn = true;
                List<string> l = InitVersion();
                _crossingRoadView.cbVersion.ItemsSource = l;
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }

        }
        private void Check()
        {
            try
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("检查交路");
            }
            catch(Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            
        }
        private void Save()
        {
            try
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("保存交路");
                string draftName = null;

                string msg = ValidateCrossingRoad();
                if (!string.IsNullOrEmpty(msg))
                {
                    if (!MessageBoxHelper.ConfirmYesNo(msg))
                        return;
                }

                if (_crossingRoadView.cbVersion.SelectedIndex < 0)
                {
                    MessageBoxHelper.ShowError("保存失败！请选择一个版本！");
                    return;
                }
                else if (_crossingRoadView.cbVersion.SelectedIndex == 0)
                {
                    if (_isCrossRoadIn)
                    {
                        if (!MessageBoxHelper.ConfirmYesNo("该时刻表已生成出勤表，是否删除先前记录？"))
                            return;

                        if (!_crossingRoadAccess.DeleCrossingRoad(TimeTable.ID))
                        {
                            MessageBoxHelper.ShowError("保存失败！执行保存操作时异常！");
                            return;
                        }
                    }
                }
                else if (_crossingRoadView.cbVersion.SelectedIndex == _crossingRoadView.cbVersion.Items.Count - 1)
                {
                    bool b = true;
                    //判断草稿名是否存在
                    while (b)
                    {
                        InputDraftNameForm f = new InputDraftNameForm();
                        if (DialogResult.Yes == f.ShowDialog())
                        {
                            draftName = InputDraftNameForm.DraftName;
                            var list = _crossingRoadView.cbVersion.ItemsSource as List<String>;

                            bool failed = false;
                            for (int i = 0; i < list.Count; i++)
                            {
                                if (list[i] == draftName)
                                {
                                    failed = true;
                                    break;
                                }
                            }
                            //如果不存在重复草稿，那么结束循环
                            if (!failed)
                                b = false;
                        }
                        else
                        {
                            return;
                        }
                    }

                }
                else
                {
                    draftName = _crossingRoadView.cbVersion.SelectedItem.ToString();
                    _crossingRoadAccess.DeleteDraft(TimeTable.ID, draftName);
                }


                DataTable dt = GetSaveTable(draftName);
                if (null == dt || dt.Rows.Count < 1)
                {
                    MessageBoxHelper.ShowError("未能保存空数据集！");
                    return;
                }
                if (_crossingRoadAccess.SaveNewCrossingRoad(dt, draftName))
                    MessageBoxHelper.ShowTips("保存交路表成功！");
                else
                    MessageBoxHelper.ShowTips("保存交路表失败！");

                //SaveTimeConfig();
                SaveParametersMethod();

                _isCrossRoadIn = true;
                List<string> l = InitVersion();
                _crossingRoadView.cbVersion.ItemsSource = l;

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
            }
        }
        public void Dg_MenuItem_Merge_Command_Method()
        {
            try
            {
                List<CrossingRoadObject> mergeList = new List<CrossingRoadObject>();
                List<SmallTrain> crossingRoadTrainList = new List<SmallTrain>();

                foreach (var item in _crossingRoadView.ClassList)
                {
                    foreach (var selected in item.SelectedItems)
                    {
                        var cr = selected as CrossingRoadObject;
                        //
                        if (mergeList.Count == 0)
                        {
                            mergeList.Add(cr);
                        }
                        else
                        {
                            for (int p = 0; p < mergeList.Count; p++)
                            {
                                if (string.Compare(mergeList[p].PlanTime, cr.PlanTime) >= 0)
                                {
                                    mergeList.Insert(p, cr);
                                    break;
                                }
                                else if (p == mergeList.Count - 1)
                                {
                                    mergeList.Add(cr);
                                    break;
                                }
                            }
                        }

                        //从crossingroad的StringCrossingRoad获取每个车次，并且按照开车时间的先后顺序装载进LIST
                        var matchs = Regex.Matches(cr.StringCrossingRoad, "[0-9]{5}");
                        foreach (Match match in matchs)
                        {
                            string trainid = match.Value;
                            SmallTrain train = TrainDictionary[trainid];
                            if (crossingRoadTrainList.Contains(train))
                                continue;
                            if (crossingRoadTrainList.Count == 0)
                            {
                                crossingRoadTrainList.Add(train);
                            }
                            else
                            {
                                for (int i = 0; i < crossingRoadTrainList.Count; i++)
                                {
                                    var currentTrain = crossingRoadTrainList[i];
                                    if (train.BeginTime < currentTrain.BeginTime)
                                    {
                                        crossingRoadTrainList.Insert(i, train);
                                        break;
                                    }
                                    else if (i == crossingRoadTrainList.Count - 1)
                                    {

                                        crossingRoadTrainList.Add(train);
                                        break; ;
                                    }
                                }
                            }
                        }
                    }
                }
                if (mergeList.Count <= 1)
                    return;
                if (MessageBoxHelper.ConfirmYesNo("确定要合并交路吗"))
                {
                    CrossingRoadObject first = mergeList[0];
                    CrossingRoadObject last = mergeList[mergeList.Count - 1];
                    first.OffPlace = last.OffPlace;
                    first.StringCrossingRoad = GetTrainListString(crossingRoadTrainList, first.AttenPlace, first.OffPlace);
                    first.OffTime = last.OffTime;
                    first.OffTrain = last.OffTrain;
                    first.OffPlace = last.OffPlace;
                    first.Miles = mergeList.Sum(item => Convert.ToDecimal(item.Miles)).ToString();
                    first.Whours = mergeList.Sum(item => Convert.ToDecimal(item.Whours)).ToString();
                    for (int i = 1; i < mergeList.Count; i++)
                    {
                        var crossingroad = mergeList[i];
                        foreach (var item in classList)
                        {
                            if (item.Contains(crossingroad))
                                item.Remove(crossingroad);
                        }
                    }
                    //CrossingRoadModel roadModel = new CrossingRoadModel();
                    //roadModel = mergeList[0].RepTrain;
                    //roadModel.AttenPlace = AttenPlace;
                    //roadModel.OffPlace = OffPlace;
                    //roadModel.StringCrossingRoad = _editorView.GetTrainList(AttenPlace, OffPlace);
                    //roadModel.PlanTime = _editorView.GetTime("ctl_planTime");
                    //roadModel.TrainTime = _editorView.GetTime("ctl_trainTime");
                    //roadModel.OffTime = _editorView.GetTime("ctl_offTime");
                    //SmallTrain offTrain = _editorView.GetOffTrain();
                    //if (null != offTrain)
                    //    roadModel.OffTrain = _editorView.GetOffTrain().TrainID;
                    //roadModel.Miles = Miles;
                    //roadModel.Whours = Hours;
                    //roadModel.Notes = Note;
                    //if (roadModel.AttenPlace == "启工街站" || roadModel.AttenPlace == "青年大街站")
                    //    roadModel.midStart = 1;
                    //if (roadModel.OffPlace == "启工街站" || roadModel.OffPlace == "青年大街站")
                    //    roadModel.midOut = 1;
                    //roadModel.type = GetRoadType();
                    //SmallTrain BcBackT = _editorView.cBoBox_bcBack.SelectedItem as SmallTrain;
                    //SmallTrain lastT = _editorView.GetOffTrain();
                    //if (null != BcBackT)
                    //{
                    //    roadModel.BCBackGarageTrainID = BcBackT.TrainID;
                    //    //roadModel.OffTime = GlobalVariables.FormatTime(BcBackT.EndTime.ToString());
                    //    roadModel.OffTrain = BcBackT.TrainID;
                    //}
                    //else
                    //{
                    //    roadModel.BCBackGarageTrainID = "";
                    //}
                    //if (null != lastT)
                    //{
                    //    roadModel.lastTrainTime = GlobalVariables.FormatTime(lastT.EndTime.ToString());
                    //}
                    //else
                    //{
                    //    roadModel.lastTrainTime = "";
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }
        public static string GetTrainListString(List<SmallTrain> list, string attenP, string offP)
        {
            string stringRunTrain = string.Empty;

            if (list == null || list.Count < 1)
                return null;

            for (int i = 0; i < list.Count; i++)
            {
                string id = list[i].TrainID;
                //int beginT = list[i].BeginTime;
                //int EndT = list[i].EndTime;
                int beginT = list[i].TimeAtFstSta < list[i].TimeAtLstSta ? list[i].TimeAtFstSta : list[i].TimeAtLstSta;

                int EndT = -1;
                if (list[i].IsLastTrip)
                {
                    EndT = list[i].EndTime;
                }
                else
                    EndT = list[i].TimeAtFstSta < list[i].TimeAtLstSta ? list[i].TimeAtLstSta : list[i].TimeAtFstSta;

                if (i == 0 && (attenP == "启工街站" || attenP == "青年大街站"))
                    beginT = list[i].TimeLeaveChangePoint;

                if (i == list.Count - 1 && (offP == "启工街站" || offP == "青年大街站"))
                    EndT = list[i].TimeAtChangePoint;

                string str = string.Format("{0}({1},{2})--->", id,
                    GlobalVariables.FormatTime(beginT.ToString()),
                    GlobalVariables.FormatTime(EndT.ToString())
                    );

                if (list[i].IsLastTrip)
                    str = str.Insert(str.IndexOf(')') + 1, "[库]");

                stringRunTrain += str;
            }

            if (null != stringRunTrain)
                stringRunTrain = stringRunTrain.Substring(0, stringRunTrain.Length - 4); //去除最后一个 "--->"

            return stringRunTrain;
        }
        public void Dg_MenuItem_Command_Method(object parameter)
        {
            string content = (string)parameter;
            string[] paras = content.Split(';');
            if (paras.Length != 2)
                return;

            string _cls = paras[0];
            string _cmd = paras[1];

            CrossingRoadObject row = null;

            EditingAction = "Add";

            if (_cmd != "Add")   //删除及编辑操作
            {
                row = _crossingRoadView.GetSelectedRow(_cls);
                if (row == null)  //如果是编辑，但是获取到的又是一空行，则提示出错
                {
                    MessageBoxHelper.ShowError("无法获取当前行信息，请先选择需要操作的行");
                    return;
                }

                if (_cmd == "Delete")
                {
                    //执行删除行的操作，
                    if (!DeleteRow(_cls, row))
                    {
                        MessageBoxHelper.ShowError("删除失败！");
                        return;
                    }
                    //删除成功后更新交路的序号
                    UpdateIndex(_cls);
                    return;
                }

                EditingRow = row;
                EditingAction = "Edit";
            }

            EditingCls = _cls;

            CrossRoadEditorParameter para = CrossRoadEditorParameter.CreateCrossRoadEditorParameter
                (
                this._garageAhead,
                this._garageBCAhead,
                this._normalAhead,
                Convert.ToInt32(this._garageDelay) * 60,
                Convert.ToInt32(this._normalDelay) * 60,
                this._outMiles,
                this._inMiles,
                this._totalMiles,
                this._upToChangedMiles,
                this._downToChangedMiles,
                this._hKHUpToChangedMiles,
                this._hKHTotalMiles
                );
            this._crossRoadEditor = new CrossRoadEditor(row, para);
            _crossRoadEditor.CommitEvent += new EventHandler<CommitArgs>(_crossiRoadEditor_CommitEvent);
            this._crossRoadEditor.ShowDialog();
        }

        void _crossiRoadEditor_CommitEvent(object sender, CommitArgs e)
        {
            CrossingRoadObject newrow = e.RowInfo;
            if (newrow == null || string.IsNullOrEmpty(EditingCls) || string.IsNullOrEmpty(EditingAction))
                return;
            int index = 0;
            foreach (var item in classList)
            {
                if (item.Contains(EditingRow))
                {
                    index = item.IndexOf(EditingRow);
                    break;
                }
            }
            if (EditingAction == "Edit")
            {
                if (!DeleteRow(EditingCls, EditingRow))
                {
                    MessageBoxHelper.ShowError("执行编辑更新出现异常，请重试！");
                    return;
                }
            }

            if (!AddRow(EditingCls, newrow, index))
                MessageBoxHelper.ShowError("尝试插入新行异常，请重试！");

            //UpdateIndex(EditingCls);

            EditingAction = null;
            EditingCls = null;
            EditingRow = null;
        }
        private bool AddRow(string cls, CrossingRoadObject row)
        {
            bool result = true;
            switch (cls)
            {
                case "ZB":

                    _crossingRoadZB.Add(row);
                    row.CrossingRoadCol = _crossingRoadZB;
                    break;
                case "BB":
                    _crossingRoadBB.Add(row);
                    row.CrossingRoadCol = _crossingRoadBB;
                    break;
                case "YB":
                    _crossingRoadYB.Add(row);
                    row.CrossingRoadCol = _crossingRoadYB;
                    break;
                default:
                    result = false;
                    break;
            }
            return result;
        }
        private bool AddRow(string cls, CrossingRoadObject row, int index)
        {
            bool result = true;
            row.ID = (index + 1).ToString();
            switch (cls)
            {
                case "ZB":
                    _crossingRoadZB.Insert(index, row);
                    row.CrossingRoadCol = _crossingRoadZB;
                    break;
                case "BB":
                    _crossingRoadBB.Insert(index, row);
                    row.CrossingRoadCol = _crossingRoadBB;
                    break;
                case "YB":
                    _crossingRoadYB.Insert(index, row);
                    row.CrossingRoadCol = _crossingRoadYB;
                    break;
                default:
                    result = false;
                    break;
            }
            return result;
        }
        private bool AddRow(int cls, CrossingRoadObject row)
        {
            bool result = true;
            switch (cls)
            {
                case 0:

                    _crossingRoadZB.Add(row);
                    row.CrossingRoadCol = _crossingRoadZB;
                    break;
                case 2:
                    _crossingRoadBB.Add(row);
                    row.CrossingRoadCol = _crossingRoadBB;
                    break;
                case 3:
                    _crossingRoadYB.Add(row);
                    row.CrossingRoadCol = _crossingRoadYB;
                    break;
                default:
                    result = false;
                    break;
            }
            return result;
        }

        private bool DeleteRow(string cls, CrossingRoadObject row)
        {
            bool result = true;
            switch (cls)
            {
                case "ZB":
                    if (_crossingRoadZB.Contains(row))
                        _crossingRoadZB.Remove(row);
                    break;
                case "BB":
                    if (_crossingRoadBB.Contains(row))
                        _crossingRoadBB.Remove(row);
                    break;
                case "YB":
                    if (_crossingRoadYB.Contains(row))
                        _crossingRoadYB.Remove(row);
                    break;
                default:
                    result = false;
                    break;
            }
            return result;
        }

        public void WarnColorCommand_Method()
        {
            _crossingRoadColorConfigView = new CrossingRoadColorConfigView(this._warnColorConfig);
            _crossingRoadColorConfigView.CommitEvent += new EventHandler(_crossingRoadColorConfigView_CommitEvent);

            _crossingRoadColorConfigView.ShowDialog();
        }

        void _crossingRoadColorConfigView_CommitEvent(object sender, EventArgs e)
        {
            this.loadWarnColorConfig();

            CrossingRoadZB.UpdateCollection();
            CrossingRoadBB.UpdateCollection();
            CrossingRoadYB.UpdateCollection();
        }

        /// <summary>
        /// 检查是否有该时刻表对应可用的交路表
        /// </summary>
        public void CheckIsCrossingRoadIn()
        {

            _isCrossRoadIn = _crossingRoadAccess.CheckHasCrossRoad(TimeTable.ID);
        }

        public void ClearCrossingRoad()
        {
            _crossingRoadZB.Clear();
            _crossingRoadBB.Clear();
            _crossingRoadYB.Clear();
        }
        ///旧的参数保存方式，已注释
        //private void SaveTimeConfig()
        //{
        //    try
        //    {
        //        string changeZb = GlobalVariables.FormatTime(_crossingRoadView.stp_zb.GetTimeSecond().ToString());

        //        string changeby = GlobalVariables.FormatTime(_crossingRoadView.stp_by.GetTimeSecond().ToString());

        //        string zbouttime = GlobalVariables.FormatTime(_crossingRoadView.stp_outZB.GetTimeSecond().ToString());

        //        string zbbacktime = GlobalVariables.FormatTime(_crossingRoadView.stp_backZB.GetTimeSecond().ToString());

        //        string bbouttime = GlobalVariables.FormatTime(_crossingRoadView.stp_outBB.GetTimeSecond().ToString());

        //        string lunchtime = GlobalVariables.FormatTime(_crossingRoadView.lunch_time.GetTimeSecond().ToString());

        //        string dinertime = GlobalVariables.FormatTime(_crossingRoadView.dinner_time.GetTimeSecond().ToString());

        //        string lunchNum = this.LunchCrossRoadCount;

        //        string supperNum = this.SupperCrossRoadCount;

        //        string restTime = this._restTime;
        //        string mealRestTime = this._mealRestTime;
        //        string garageAhead = this._garageAhead;
        //        string garageBCAhead = this._garageBCAhead;
        //        string normalAhead = this._normalAhead;

        //        string tableBame = TimeTable.Name;

        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "changeZb", changeZb);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "changeby", changeby);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "zbouttime", zbouttime);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "zbbacktime", zbbacktime);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "bbouttime", bbouttime);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "lunchtime", lunchtime);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "dinertime", dinertime);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "lunchNum", lunchNum);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "supperNum", supperNum);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "restTime", restTime);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "mealRestTime", mealRestTime);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "garageAhead", garageAhead);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "garageBCAhead", garageBCAhead);
        //        _crossingRoadView.iniFileHelper.WriteString(tableBame, "normalAhead", normalAhead);
        //    }
        //    catch (System.Exception ex)
        //    {

        //    }
        //}

        public void loadWarnColorConfig()
        {
            double maxZB = ColorConfig.DefaultMax;
            double maxBB = ColorConfig.DefaultMax;
            double maxYB = ColorConfig.DefaultMax;
            Color _tempCorlor = ColorConfig.DefaultColor;
            if (_crossingRoadColorConfigAccess.LoadMilesConfig(ref _tempCorlor, ref maxZB, ref maxBB, ref maxYB))
            {
                this._warnColorConfig.WarnColorMiles = _tempCorlor;
                this._warnColorConfig.WarnMilesZB = maxZB;
                this._warnColorConfig.WarnMilesBB = maxBB;
                this._warnColorConfig.WarnMilesYB = maxYB;
            }

            if (_crossingRoadColorConfigAccess.LoadWhoursConfig(ref _tempCorlor, ref maxZB, ref maxBB, ref maxYB))
            {
                this._warnColorConfig.WarnColorWhours = _tempCorlor;
                this._warnColorConfig.WarnWhourZB = maxZB;
                this._warnColorConfig.WarnWhourBB = maxBB;
                this._warnColorConfig.WarnWhourYB = maxYB;
            }
        }
        /// <summary>
        /// 载入已经存在的时刻表对应的交路表
        /// </summary>
        public void LoadCrossingRoadDraft(string draftName)
        {
            DataTable allRoadsDT = _crossingRoadAccess.GetCrossingRoadDraft(TimeTable.ID, draftName);
            LoadCrossingRoad(allRoadsDT);
        }
        private void LoadCrossingRoad(DataTable allRoadsDT)
        {
            if (null == allRoadsDT || allRoadsDT.Rows.Count < 1)
                return;

            for (int i = 0; i < allRoadsDT.Rows.Count; i++)
            {
                CrossingRoadModel model = CrossingRoadModel.CreateCrossingRoadModel();
                model.ID = allRoadsDT.Rows[i]["number"].ToString();
                model.type = allRoadsDT.Rows[i]["type"].ToString();
                model.AttenPlace = allRoadsDT.Rows[i]["attenPlace"].ToString();
                model.PlanTime = allRoadsDT.Rows[i]["attenTime"].ToString();
                model.TrainTime = allRoadsDT.Rows[i]["trainTime"].ToString();
                model.RepTrain = allRoadsDT.Rows[i]["reptrain"].ToString();
                model.StringCrossingRoad = allRoadsDT.Rows[i]["stringRunTrain"].ToString();
                model.OffTrain = allRoadsDT.Rows[i]["offTrain"].ToString();
                model.BCBackGarageTrainID = allRoadsDT.Rows[i]["bCBackGarageTrainID"].ToString();
                model.midStart = Convert.ToInt32(allRoadsDT.Rows[i]["midStart"]);
                model.midOut = Convert.ToInt32(allRoadsDT.Rows[i]["midOut"]);
                model.OffTime = allRoadsDT.Rows[i]["offTime"].ToString();
                model.OffPlace = allRoadsDT.Rows[i]["offPlace"].ToString();
                model.Miles = allRoadsDT.Rows[i]["miles"].ToString();
                model.Whours = allRoadsDT.Rows[i]["wHours"].ToString();
                model.Notes = allRoadsDT.Rows[i]["notes"].ToString();
                model.lastTrainTime = allRoadsDT.Rows[i]["lastTrainTime"].ToString();
                model.CrName = allRoadsDT.Rows[i]["CrName"].ToString();

                int _class = Convert.ToInt32(allRoadsDT.Rows[i]["zby"]);

                var row = new CrossingRoadObject(model);
                AddRow(_class, row);
                if (allRoadsDT.Rows[i]["lastModifiedTime"] != DBNull.Value)
                    LastModifiedTime = allRoadsDT.Rows[i]["lastModifiedTime"].ToString();
                if (allRoadsDT.Rows[i]["lastModifier"] != DBNull.Value)
                    LastModifier = allRoadsDT.Rows[i]["lastModifier"].ToString();
            }
        }
        /// <summary>
        /// 载入已经存在的时刻表对应的交路表
        /// </summary>
        public void LoadExistCrossingRoad()
        {
            DataTable allRoadsDT = _crossingRoadAccess.GetExistCrossingRoad(TimeTable.ID);

            LoadCrossingRoad(allRoadsDT);

        }
        public void DeleteDraft(string draftName)
        {
            _crossingRoadAccess.DeleteDraft(TimeTable.ID, draftName);
        }
        private DataTable GetSaveTable(string draftName)
        {
            try
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("获取要保持的交路表");
                if (_crossingRoadZB.Count < 1 || _crossingRoadBB.Count < 1 || _crossingRoadYB.Count < 1)
                {
                    Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("获取要保持的交路表 NULL");
                    return null;
                }

                DataTable dt = new DataTable();

                dt.Columns.Add(new DataColumn("tableInfo_id", typeof(System.Int32)));
                dt.Columns.Add(new DataColumn("zby", typeof(System.Int32)));
                dt.Columns.Add(new DataColumn("number", typeof(System.Int32)));
                dt.Columns.Add(new DataColumn("grp_id", typeof(System.Int32)));
                dt.Columns.Add(new DataColumn("attenPlace", typeof(System.String)));
                dt.Columns.Add(new DataColumn("attenTime", typeof(System.String)));
                dt.Columns.Add(new DataColumn("trainTime", typeof(System.String)));
                dt.Columns.Add(new DataColumn("reptrain", typeof(System.String)));
                dt.Columns.Add(new DataColumn("stringRunTrain", typeof(System.String)));
                dt.Columns.Add(new DataColumn("offTrain", typeof(System.String)));
                dt.Columns.Add(new DataColumn("bCBackGarageTrainID", typeof(System.String)));
                dt.Columns.Add(new DataColumn("midStart", typeof(System.Int32)));
                dt.Columns.Add(new DataColumn("midOut", typeof(System.Int32)));
                dt.Columns.Add(new DataColumn("lastTrainTime", typeof(System.String)));
                dt.Columns.Add(new DataColumn("offTime", typeof(System.String)));
                dt.Columns.Add(new DataColumn("offPlace", typeof(System.String)));
                dt.Columns.Add(new DataColumn("miles", typeof(System.String)));
                dt.Columns.Add(new DataColumn("wHours", typeof(System.String)));
                dt.Columns.Add(new DataColumn("notes", typeof(System.String)));
                var isCol = new DataColumn("isused", typeof(System.Int32));
                isCol.DefaultValue = 1;
                dt.Columns.Add(isCol);
                //草稿版
                if (!string.IsNullOrEmpty(draftName))
                {
                    var dnCol = new DataColumn("draftName", typeof(System.String));
                    dnCol.DefaultValue = draftName;
                    dt.Columns.Add(dnCol);
                }
                var lmtCol = new DataColumn("lastModifiedTime", typeof(System.DateTime));
                lmtCol.DefaultValue = DateTime.Now;
                dt.Columns.Add(lmtCol);

                var lmCol = new DataColumn("lastModifier", typeof(int));
                lmCol.DefaultValue = Convert.ToInt32(CONSTDATA.UserModel.ID);
                dt.Columns.Add(lmCol);
                dt.Columns.Add(new DataColumn("CrName", typeof(System.String)));

                for (int i = 0; i < _crossingRoadZB.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["tableInfo_id"] = TimeTable.ID;
                    dr["zby"] = 0;
                    dr["number"] = _crossingRoadZB[i].ID;
                    dr["grp_id"] = GetGroupTypeByName(_crossingRoadZB[i].type);
                    dr["attenPlace"] = _crossingRoadZB[i].AttenPlace;
                    dr["attenTime"] = _crossingRoadZB[i].PlanTime;
                    dr["TrainTime"] = _crossingRoadZB[i].TrainTime;
                    dr["reptrain"] = _crossingRoadZB[i].RepTrain;
                    dr["stringRunTrain"] = _crossingRoadZB[i].StringCrossingRoad;
                    dr["bCBackGarageTrainID"] = _crossingRoadZB[i].BCBackGarageTrainID;
                    dr["offTrain"] = _crossingRoadZB[i].OffTrain;
                    dr["midStart"] = _crossingRoadZB[i].midStart;
                    dr["midOut"] = _crossingRoadZB[i].midOut;
                    dr["lastTrainTime"] = _crossingRoadZB[i].lastTrainTime;
                    dr["offTime"] = _crossingRoadZB[i].OffTime;
                    dr["offPlace"] = _crossingRoadZB[i].OffPlace;
                    dr["Miles"] = _crossingRoadZB[i].Miles;
                    dr["wHours"] = _crossingRoadZB[i].Whours;
                    dr["notes"] = _crossingRoadZB[i].Notes;
                    dr["CrName"] = _crossingRoadZB[i].CrName;

                    dt.Rows.Add(dr);
                }

                for (int i = 0; i < _crossingRoadBB.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["tableInfo_id"] = TimeTable.ID;
                    dr["zby"] = 2;
                    dr["number"] = _crossingRoadBB[i].ID;
                    dr["grp_id"] = GetGroupTypeByName(_crossingRoadBB[i].type);
                    dr["attenPlace"] = _crossingRoadBB[i].AttenPlace;
                    dr["attenTime"] = _crossingRoadBB[i].PlanTime;
                    dr["TrainTime"] = _crossingRoadBB[i].TrainTime;
                    dr["reptrain"] = _crossingRoadBB[i].RepTrain;
                    dr["stringRunTrain"] = _crossingRoadBB[i].StringCrossingRoad;
                    dr["offTrain"] = _crossingRoadBB[i].OffTrain;
                    dr["bCBackGarageTrainID"] = _crossingRoadBB[i].BCBackGarageTrainID;
                    dr["midStart"] = _crossingRoadBB[i].midStart;
                    dr["midOut"] = _crossingRoadBB[i].midOut;
                    dr["lastTrainTime"] = _crossingRoadBB[i].lastTrainTime;
                    dr["offTime"] = _crossingRoadBB[i].OffTime;
                    dr["offPlace"] = _crossingRoadBB[i].OffPlace;
                    dr["Miles"] = _crossingRoadBB[i].Miles;
                    dr["wHours"] = _crossingRoadBB[i].Whours;
                    dr["notes"] = _crossingRoadBB[i].Notes;
                    dr["CrName"] = _crossingRoadBB[i].CrName;
                    dt.Rows.Add(dr);
                }

                for (int i = 0; i < _crossingRoadYB.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["tableInfo_id"] = TimeTable.ID;
                    dr["zby"] = 3;
                    dr["number"] = _crossingRoadYB[i].ID;
                    dr["grp_id"] = GetGroupTypeByName(_crossingRoadYB[i].type);
                    dr["attenPlace"] = _crossingRoadYB[i].AttenPlace;
                    dr["attenTime"] = _crossingRoadYB[i].PlanTime;
                    dr["TrainTime"] = _crossingRoadYB[i].TrainTime;
                    dr["reptrain"] = _crossingRoadYB[i].RepTrain;
                    dr["stringRunTrain"] = _crossingRoadYB[i].StringCrossingRoad;
                    dr["offTrain"] = _crossingRoadYB[i].OffTrain;
                    dr["bCBackGarageTrainID"] = _crossingRoadYB[i].BCBackGarageTrainID;
                    dr["midStart"] = _crossingRoadYB[i].midStart;
                    dr["midOut"] = _crossingRoadYB[i].midOut;
                    dr["lastTrainTime"] = _crossingRoadYB[i].lastTrainTime;
                    dr["offTime"] = _crossingRoadYB[i].OffTime;
                    dr["offPlace"] = _crossingRoadYB[i].OffPlace;
                    dr["Miles"] = _crossingRoadYB[i].Miles;
                    dr["wHours"] = _crossingRoadYB[i].Whours;
                    dr["notes"] = _crossingRoadYB[i].Notes;
                    dr["CrName"] = _crossingRoadYB[i].CrName;

                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch (Exception ex)
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
                return null;
            }
        }

        private int GetGroupTypeByName(string _type)
        {
            int typeId = 5;

            this.Group.TryGetValue(_type, out typeId);

            return typeId;
        }

        private void ExportCommand_Method()
        {
            if (_timeTable == null)
            {
                MessageBoxHelper.ShowError("请先选择需要导出的时刻表！");
                return;
            }
            if (_crossingRoadZB.Count < 1 && _crossingRoadBB.Count < 1 && _crossingRoadYB.Count < 1)
            {
                MessageBoxHelper.ShowError("该时刻表尚未有相应的交路表信息，请确认！");
                return;
            }

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.Description = "请选择交路表的保存路径";
            if (fbd.ShowDialog() == DialogResult.Cancel)
            {
                IsExporting = false;
                return;
            }

            filePath = fbd.SelectedPath;
            if (!filePath.EndsWith("\\"))
                filePath += "\\";

            if (null == ExportExcelThread)
            {
                ExportExcelThread = new Thread(new ThreadStart(ExportExcel));
                ExportExcelThread.SetApartmentState(ApartmentState.STA);
                ExportExcelThread.IsBackground = true;
            }
            else
            {
                ExportExcelThread.Abort();
                ExportExcelThread = new Thread(new ThreadStart(ExportExcel));
                ExportExcelThread.SetApartmentState(ApartmentState.STA);
                ExportExcelThread.IsBackground = true;
            }

            ExportExcelThread.Start();

            IsExporting = true;

            ExportInfoVisibility = Visibility.Visible;
        }

        private void ExportTimeTable_Method()
        {
            if (_timeTable == null)
            {
                MessageBoxHelper.ShowError("请先选择需要导出的时刻表！");
                return;
            }
            if (_crossingRoadZB.Count < 1 && _crossingRoadBB.Count < 1 && _crossingRoadYB.Count < 1)
            {
                MessageBoxHelper.ShowError("该时刻表尚未有相应的交路表信息，请确认！");
                return;
            }

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.Description = "请选择时刻表的保存路径";
            if (fbd.ShowDialog() == DialogResult.Cancel)
            {
                IsExporting = false;
                return;
            }

            filePath = fbd.SelectedPath;
            if (!filePath.EndsWith("\\"))
                filePath += "\\";

            if (null == ExportExcelThread)
            {
                ExportExcelThread = new Thread(new ThreadStart(ExportTimeTableExcel));
                ExportExcelThread.SetApartmentState(ApartmentState.STA);
                ExportExcelThread.IsBackground = true;
            }
            else
            {
                ExportExcelThread.Abort();
                ExportExcelThread = new Thread(new ThreadStart(ExportTimeTableExcel));
                ExportExcelThread.SetApartmentState(ApartmentState.STA);
                ExportExcelThread.IsBackground = true;
            }

            ExportExcelThread.Start();

            IsExporting = true;

            ExportInfoVisibility = Visibility.Visible;
        }

        private void ExportTimeTableExcel()
        {
            string fileName = string.Format("{0}时刻表_{1}.xls", _timeTable.Name, DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));
            string FileHeader = string.Format("{0} 时刻表", _timeTable.Name);

            List<Station> list = new List<Station>();
            SqlDataLayer sqlHelper = new SqlDataLayer();
            Dictionary<int, string> StationID_To_Name;
            Dictionary<int, int> sortDis;
            if (CONSTDATA.UserModel.Line == "1")
            {
                StationID_To_Name = CONSTDATA.InitStationID_To_Name_1();
            }
            else
            {
                StationID_To_Name = CONSTDATA.InitStationID_To_Name_2();
            }
            if (CONSTDATA.UserModel.Line == "1")
            {
                sortDis = CONSTDATA.InitStationSort_To_Name_1();
            }
            else
            {
                sortDis = CONSTDATA.InitStationSort_To_Name_2();
            }

            foreach (var item in StationID_To_Name)
            {

                if (item.Key >= 30 && item.Key <= 40)
                    continue;
                Station model = new Station();
                model.ID = item.Key;
                model.StationName = item.Value;
                list.Add(model);

            }
            list.Sort((x, y) =>
            {
                return sortDis[x.ID] - sortDis[y.ID];
            });

            string sqlstr = "select * from TableInfo where TableName='" + _timeTable.Name + "'";
            DataTable dt = sqlHelper.SelectDt(sqlstr);

            //string sql_traininfo = "select distinct A.TrainID,A.LastID,B.TBegin,A.Arrive,A.Depart,A.Start,A.Destiny,B.TEnd, DID,(select case when exists (select a1.arc_ne  from [" + _timeTable.Name + "] as a1 where a1.trainid=a.trainid and a1.arc_ne='#####') then 1 else 0 end) as IsLastTrip from [" + _timeTable.Name
            //    + "] A left join TrainDetailInfo B on A.TrainID = B.TrainID   where A.Station = '10' and B.tableInfo_id = '" + dt.Rows[0]["ID"] + "' order by TBegin";
            //DataTable dt_traininfo = sqlHelper.SelectDt(sql_traininfo);
            //下行数据
            string sqlstr2 = "select TrainID,Station,Direction,Arrive,Depart from [" + _timeTable.Name + "] where Direction='1'";
            DataTable DownTrain = sqlHelper.SelectDt(sqlstr2);
            //上行数据
            string sqlstr3 = "select TrainID,Station,Direction,Arrive,Depart from [" + _timeTable.Name + "] where Direction='2'";
            DataTable UpTrain = sqlHelper.SelectDt(sqlstr3);

            //获取下行车次数数据
            string sqlstr4 = "select distinct TrainID,Direction from [" + _timeTable.Name + "] where Direction='1'";
            DataTable DownTrainNum = sqlHelper.SelectDt(sqlstr4);
            //获取上行车次数数据
            string sqlstr5 = "select distinct TrainID,Direction from [" + _timeTable.Name + "] where Direction='2'";
            DataTable UpTrainNum = sqlHelper.SelectDt(sqlstr5);

            string sqlstr6 = "select zby,stringRunTrain,CrName,reptrain,notes from CrossingRoad where tableInfo_id='" + dt.Rows[0]["ID"] + "' and isused='1'";
            DataTable CrossDt = sqlHelper.SelectDt(sqlstr6);

            DataRow[] bianchengRows = CrossDt.Select("reptrain like '(便)%'");
            DataRow[] wanBcRows= CrossDt.Select("notes like '%便%'");


            //获取下行车次排序
            string sqlstr7 = "select * from (select TrainID,Direction,Depart,row_number() over (partition by TrainID order by Depart) rn from  [" + _timeTable.Name + "] where Arrive='0') s where rn='1' and Direction='1' order by Depart";
            DataTable DownTrainorderby = sqlHelper.SelectDt(sqlstr7);
            //获取上行车次排序
            string sqlstr8 = "select * from (select TrainID,Direction,Depart,row_number() over (partition by TrainID order by Depart) rn from  [" + _timeTable.Name + "] where Arrive='0') s where rn='1' and Direction='2' order by Depart";
            DataTable UpTrainorderby = sqlHelper.SelectDt(sqlstr8);

            if ((null == DownTrain || DownTrain.Rows.Count < 1) && (null == UpTrain || UpTrain.Rows.Count < 1))
            {
                Console.WriteLine("初始化时刻表列车信息失败！");
                return;
            }

            try
            {
                //计算循环次数
                double DownNum = Math.Ceiling(double.Parse(DownTrainNum.Rows.Count.ToString()) / 11);
                double UpNum = Math.Ceiling(double.Parse(UpTrainNum.Rows.Count.ToString()) / 11);

                int num = 0;
                if (DownNum > UpNum)
                {
                    num = int.Parse(DownNum.ToString());
                }
                else
                {
                    num = int.Parse(UpNum.ToString());
                }

                Helper_Excel excel=new Helper_Excel();
                excel.getNewSheet(_timeTable.Name);
                //框架填写
                int startnum = 0;
                for (int i = 0; i < num; i++)
                {
                    excel.MergeCell(startnum, startnum, 0, 22);
                    excel.getCellsStyle1(startnum, 0, _timeTable.Name);
                    excel.MergeCell(startnum + 1, startnum + 1, 0, 11);
                    excel.MergeCell(startnum + 1, startnum + 1, 12, 23);
                    excel.getCellsStyle1(startnum + 1, 0, "下行线");
                    excel.getCellsStyle1(startnum + 1, 12, "上行线");
                    excel.getCellsStyle1(startnum + 1, 11, "线别");
                    excel.getCellsStyle1(startnum + 2, 11, "服务号");
                    excel.getCellsStyle1(startnum + 4, 11, "备注");

                    for (int j = 0; j < list.Count; j++)
                    {
                        excel.MergeCell(startnum + 6 + (2 * j), startnum + 7 + (2 * j), 11, 11);
                        excel.getCellsStyle1(startnum + 6 + (2 * j), 11, list[j].StationName);
                    }

                    excel.getCellsStyle1(startnum + 4 + (2 * list.Count), 11, "备注");
                    excel.getCellsStyle1(startnum + 5 + (2 * list.Count), 11, "服务号");
                    excel.getCellsStyle1(startnum + 6 + (2 * list.Count), 11, "行车间隔");
                    excel.getCellsStyle1(startnum + 7 + (2 * list.Count), 11, "第" + (i + 1) + "页");
                    startnum = startnum + (9 + (list.Count * 2));
                }

                //填写车次数据
                int downstart = 0;
                int upstart = 0;
                int rownum = 5;
                //startnum = 1;
                DataRow[] rows = null;
                DataRow[] rowss = null;
                DataRow[] crossrows = null;
                DataTable ddt = null;
                for (int i = 0; i < num; i++)
                {
                    for (int j = 10; j >= 0 && DownTrainorderby.Rows.Count - 1 >= downstart; j--)
                    {
                        string trainID = DownTrainorderby.Rows[downstart]["TrainID"].ToString();
                        rows = DownTrain.Select("TrainID='" + trainID + "'");
                        ddt = rows.CopyToDataTable();
                        crossrows = CrossDt.Select("stringRunTrain like '%" + trainID + "%'","zby");
                        if (crossrows.Length > 0 && crossrows.Length < 2)
                        {
                            excel.getCells(rownum-2, j, crossrows[0]["CrName"].ToString());
                            excel.getCells(rownum  + (2 * list.Count), j, crossrows[0]["CrName"].ToString());
                        }
                        else if (crossrows.Length > 1)
                        {
                            excel.getCells(rownum-2, j, crossrows[0]["CrName"].ToString());
                            excel.getCells(rownum  + (2 * list.Count), j, crossrows[1]["CrName"].ToString());
                        }
                        excel.getCells(rownum - 3, j, trainID);
                        for(int bcIndex = 0; bcIndex < bianchengRows.Length; bcIndex++)
                        {
                            if (bianchengRows[bcIndex]["repTrain"].ToString().Contains(trainID))
                            {
                                excel.getCells(rownum - 1, j, bianchengRows[bcIndex]["CrName"]+"便");
                            }
                        }
                        excel.getCells(rownum + 2 + (2 * list.Count), j, trainID);
                        for (int bcIndex = 0; bcIndex < wanBcRows.Length; bcIndex++)
                        {
                            if (wanBcRows[bcIndex]["notes"].ToString().Contains(trainID))
                            {
                                excel.getCells(rownum + (2 * list.Count), j, wanBcRows[bcIndex]["CrName"] + "便");
                            }
                        }
                        for (int k = 0; k < list.Count; k++)
                        {
                            rowss = ddt.Select("Station='" + list[k].ID + "'");
                            if (rowss.Length > 0)
                            {
                                excel.getCells(rownum + 1 + (2 * k), j, rowss[0]["Arrive"].ToString() != "0" ? ChangeToDate(rowss[0]["Arrive"]) : ChangeToDate(rowss[0]["Depart"]));
                                excel.getCells(rownum + 2 + (2 * k), j, rowss[0]["Depart"].ToString() != "-1" ? ChangeToDate(rowss[0]["Depart"]) : ChangeToDate(rowss[0]["Arrive"]));
                            }
                        }
                        downstart++;
                    }
                    for (int j = 12; j < 23 && UpTrainorderby.Rows.Count - 1 >= upstart; j++)
                    {
                        string trainID = UpTrainorderby.Rows[upstart]["TrainID"].ToString();
                        rows = UpTrain.Select("TrainID='" + trainID + "'");
                        ddt = rows.CopyToDataTable();
                        crossrows = CrossDt.Select("stringRunTrain like '%" + trainID + "%'", "zby");
                        if (crossrows.Length > 0 && crossrows.Length < 2)
                        {
                            excel.getCells(rownum + (2 * list.Count), j, crossrows[0]["CrName"].ToString());
                            excel.getCells(rownum-2, j, crossrows[0]["CrName"].ToString());
                        }
                        else if (crossrows.Length > 1)
                        {
                            excel.getCells(rownum  + (2 * list.Count), j, crossrows[0]["CrName"].ToString());
                            excel.getCells(rownum-2, j, crossrows[1]["CrName"].ToString());
                        }
                        excel.getCells(rownum - 3, j, trainID);
                        for (int bcIndex = 0; bcIndex < bianchengRows.Length; bcIndex++)
                        {
                            if (bianchengRows[bcIndex]["repTrain"].ToString().Contains(trainID))
                            {
                                excel.getCells(rownum - 1, j, bianchengRows[bcIndex]["CrName"] + "便");
                            }
                        }
                        excel.getCells(rownum + 2 + (2 * list.Count), j, trainID);
                        for (int bcIndex = 0; bcIndex < wanBcRows.Length; bcIndex++)
                        {
                            if (wanBcRows[bcIndex]["notes"].ToString().Contains(trainID))
                            {
                                excel.getCells(rownum + (2 * list.Count), j, wanBcRows[bcIndex]["CrName"] + "便");
                            }
                        }
                        for (int k = 0; k < list.Count; k++)
                        {
                            rowss = ddt.Select("Station='" + list[k].ID + "'");
                            if (rowss.Length > 0)
                            {
                                excel.getCells(rownum + 1 + (2 * k), j, rowss[0]["Depart"].ToString() != "-1" ? ChangeToDate(rowss[0]["Depart"]) : ChangeToDate(rowss[0]["Arrive"]));
                                excel.getCells(rownum + 2 + (2 * k), j, rowss[0]["Arrive"].ToString() != "0" ? ChangeToDate(rowss[0]["Arrive"]) : ChangeToDate(rowss[0]["Depart"]));
                            }
                        }
                        upstart++;
                    }
                    //startnum = startnum + (8 + (list.Count * 2));
                    rownum = rownum + (9 + (list.Count * 2));
                }

                //添加样式，调整宽度
                //获取当前列的宽度，然后对比本列的长度，取最大值
                int columnWidth = excel.SetCellColumnWidth(11) / 256;
                for (int i = 0; i < list.Count; i++)
                {
                    int rowNum = i + 4;
                    int length = Encoding.Default.GetBytes(excel.getCells(rowNum, 11).ToString()).Length;
                    if (columnWidth < length)
                    {
                        columnWidth = length + 1;
                    }
                }
                excel.SetCellColumnWidth(11, 11, columnWidth * 256);
                excel.GetAllBord();

                excel.SaveFile(string.Format("{0}{1}", filePath, fileName));
                MessageBoxHelper.ShowTips(string.Format("导出 {0}  成功!", FileHeader));
            }
            catch (System.Exception ex)
            {
                MessageBoxHelper.ShowError(string.Format("导出时刻表失败: {0}", ex.Message.ToString()));
            }

            IsExporting = false;
            ExportInfoVisibility = Visibility.Collapsed;
        }

        private string ChangeToDate(object obj)
        {
            long getobj = Convert.ToInt64(obj);
            if (getobj > 86400)
            {
                getobj -= 86400;
            }
            long a, b, c;
            string ret = string.Empty;
            if (getobj > 0)
            {
                a = (getobj / 3600);
                b = ((getobj % 3600) / 60);
                c = ((getobj % 3600) % 60);
                ret = a < 10 ? "0" + a.ToString() : a.ToString();
                ret += ":";
                ret += b < 10 ? "0" + b.ToString() : b.ToString();
                ret += ":";
                ret += c < 10 ? "0" + c.ToString() : c.ToString();
            }
            return ret;
        }


        private bool Can_ExportCommand_Method()
        {
            return !_isExporting;
        }

        private void ExportExcel()
        {
            string fileName = string.Format("{0}交路表_{1}.xlsx", _timeTable.Name, DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));

            string FileHeader = string.Format("{0} 交路表", _timeTable.Name);

            DataTable callZB = GetCallTable();
            DataTable callBB = GetCallTable();
            DataTable callYB = GetCallTable();

            InitCallTable(ref callZB, _crossingRoadZB);
            InitCallTable(ref callBB, _crossingRoadBB);
            InitCallTable(ref callYB, _crossingRoadYB);

            int BbIndex = _crossingRoadZB.Count + 5;
            int YbIndex = BbIndex + _crossingRoadBB.Count + 3;
            try
            {
                OutExcel excel = new OutExcel();
                excel.ws.Cells[1, 1] = FileHeader;
                excel.UniteCells(excel.ws, 1, 1, 1, 13);
                excel.ws.Cells[2, 1] = "早班";
                excel.ws.Cells[BbIndex, 1] = "白班";
                excel.ws.Cells[YbIndex, 1] = "夜班";
                excel.UniteCells(excel.ws, 2, 1, 2, 13);
                excel.UniteCells(excel.ws, BbIndex, 1, BbIndex, 13);
                excel.UniteCells(excel.ws, BbIndex - 1, 1, BbIndex - 1, 13);
                excel.UniteCells(excel.ws, YbIndex, 1, YbIndex, 13);
                excel.UniteCells(excel.ws, YbIndex - 1, 1, YbIndex - 1, 13);
                excel.ws.Cells[3, 1] = excel.ws.Cells[BbIndex + 1, 1] = excel.ws.Cells[YbIndex + 1, 1] = "交路号";  // A
                excel.ws.Cells[3, 2] = excel.ws.Cells[BbIndex + 1, 2] = excel.ws.Cells[YbIndex + 1, 2] = "类别"; // B
                excel.ws.Cells[3, 3] = excel.ws.Cells[BbIndex + 1, 3] = excel.ws.Cells[YbIndex + 1, 3] = "出勤地点"; // C
                excel.ws.Cells[3, 4] = excel.ws.Cells[BbIndex + 1, 4] = excel.ws.Cells[YbIndex + 1, 4] = "出勤时间"; // D
                excel.ws.Cells[3, 5] = excel.ws.Cells[BbIndex + 1, 5] = excel.ws.Cells[YbIndex + 1, 5] = "发车时间";// E
                excel.ws.Cells[3, 6] = excel.ws.Cells[BbIndex + 1, 6] = excel.ws.Cells[YbIndex + 1, 6] = "接班车次";// F
                excel.ws.Cells[3, 7] = excel.ws.Cells[BbIndex + 1, 7] = excel.ws.Cells[YbIndex + 1, 7] = "开行交路";// G
                excel.ws.Cells[3, 8] = excel.ws.Cells[BbIndex + 1, 8] = excel.ws.Cells[YbIndex + 1, 8] = "退勤车次";// H
                excel.ws.Cells[3, 9] = excel.ws.Cells[BbIndex + 1, 9] = excel.ws.Cells[YbIndex + 1, 9] = "退勤地点";// I
                excel.ws.Cells[3, 10] = excel.ws.Cells[BbIndex + 1, 10] = excel.ws.Cells[YbIndex + 1, 10] = "退勤时间";// J
                excel.ws.Cells[3, 11] = excel.ws.Cells[BbIndex + 1, 11] = excel.ws.Cells[YbIndex + 1, 11] = "公里数";// K
                excel.ws.Cells[3, 12] = excel.ws.Cells[BbIndex + 1, 12] = excel.ws.Cells[YbIndex + 1, 12] = "工时";// L
                excel.ws.Cells[3, 13] = excel.ws.Cells[BbIndex + 1, 13] = excel.ws.Cells[YbIndex + 1, 13] = "备注";// M

                ((Excel.Range)excel.ws.Columns["C:C", System.Type.Missing]).ColumnWidth =
                ((Excel.Range)excel.ws.Columns["D:D", System.Type.Missing]).ColumnWidth =
                    ((Excel.Range)excel.ws.Columns["E:E", System.Type.Missing]).ColumnWidth =
                    ((Excel.Range)excel.ws.Columns["F:F", System.Type.Missing]).ColumnWidth =
                    ((Excel.Range)excel.ws.Columns["I:I", System.Type.Missing]).ColumnWidth =
                    ((Excel.Range)excel.ws.Columns["J:J", System.Type.Missing]).ColumnWidth = 12;

                ((Excel.Range)excel.ws.Columns["G:G", System.Type.Missing]).ColumnWidth = 120;
                ((Excel.Range)excel.ws.Columns["M:M", System.Type.Missing]).ColumnWidth = 30;
                ((Excel.Range)excel.ws.Cells[1, 1]).Font.Size = 22;
                ((Excel.Range)excel.ws.Cells[1, 1]).Font.Color = Excel.Constants.xlColor1;
                ((Excel.Range)excel.ws.Cells[2, 1]).Font.Size = 16;
                ((Excel.Range)excel.ws.Cells[BbIndex, 1]).Font.Size = 16;
                ((Excel.Range)excel.ws.Cells[YbIndex, 1]).Font.Size = 16;
                ((Excel.Range)excel.ws.Cells[2, 1]).RowHeight = 30;
                ((Excel.Range)excel.ws.Cells[BbIndex, 1]).RowHeight = 30;
                ((Excel.Range)excel.ws.Cells[YbIndex, 1]).RowHeight = 30;

                excel.InsertTable(callZB, excel.ws, 4, 1);
                excel.InsertTable(callBB, excel.ws, BbIndex + 2, 1);
                excel.InsertTable(callYB, excel.ws, YbIndex + 2, 1);

                excel.SaveAs(string.Format("{0}{1}", filePath, fileName));
                excel.Close();
                excel.KillExcelProcess();

                MessageBoxHelper.ShowTips(string.Format("导出 {0}  成功!", FileHeader));
            }
            catch (System.Exception ex)
            {
                MessageBoxHelper.ShowError(string.Format("导出交班表失败: {0}", ex.Message.ToString()));
            }

            IsExporting = false;
            ExportInfoVisibility = Visibility.Collapsed;
        }

        private DataTable GetCallTable()
        {
            DataTable callTable = new DataTable();

            DataColumn dc1 = new DataColumn("Num", System.Type.GetType("System.String"));         // 交路号
            DataColumn dc2 = new DataColumn("type", System.Type.GetType("System.String"));     //类别
            DataColumn dc3 = new DataColumn("CheckinPlace", System.Type.GetType("System.String"));  //出勤地点
            DataColumn dc4 = new DataColumn("CheckinTime", System.Type.GetType("System.String")); //出勤时间
            DataColumn dc5 = new DataColumn("StartTime", System.Type.GetType("System.String"));  //出车时间
            DataColumn dc6 = new DataColumn("Checi", System.Type.GetType("System.String")); //接班车次
            DataColumn dc7 = new DataColumn("JiaoLu", System.Type.GetType("System.String")); //交路
            DataColumn dc8 = new DataColumn("OutCheci", System.Type.GetType("System.String")); //退勤车次
            DataColumn dc9 = new DataColumn("OutPlace", System.Type.GetType("System.String")); //退勤地点
            DataColumn dc10 = new DataColumn("OutTime", System.Type.GetType("System.String")); //退勤时间
            DataColumn dc11 = new DataColumn("Miles", System.Type.GetType("System.String")); //公里数
            DataColumn dc12 = new DataColumn("WorkHours", System.Type.GetType("System.String")); //工时
            DataColumn dc13 = new DataColumn("Notes", System.Type.GetType("System.String")); //工时

            callTable.Columns.Add(dc1);
            callTable.Columns.Add(dc2);
            callTable.Columns.Add(dc3);
            callTable.Columns.Add(dc4);
            callTable.Columns.Add(dc5);
            callTable.Columns.Add(dc6);
            callTable.Columns.Add(dc7);
            callTable.Columns.Add(dc8);
            callTable.Columns.Add(dc9);
            callTable.Columns.Add(dc10);
            callTable.Columns.Add(dc11);
            callTable.Columns.Add(dc12);
            callTable.Columns.Add(dc13);
            return callTable;
        }

        private void InitCallTable(ref DataTable table, CrossingRoadObjects roads)
        {
            for (int i = 0; i < roads.Count; i++)
            {
                DataRow row = table.NewRow();
                row["Num"] = (roads[i] as CrossingRoadObject).ID;
                row["type"] = (roads[i] as CrossingRoadObject).type;
                row["CheckinPlace"] = (roads[i] as CrossingRoadObject).AttenPlace;
                row["CheckinTime"] = (roads[i] as CrossingRoadObject).PlanTime;
                row["StartTime"] = (roads[i] as CrossingRoadObject).TrainTime;
                row["Checi"] = (roads[i] as CrossingRoadObject).RepTrain;
                row["JiaoLu"] = (roads[i] as CrossingRoadObject).StringCrossingRoad;
                row["OutCheci"] = (roads[i] as CrossingRoadObject).OffTrain;
                row["OutPlace"] = (roads[i] as CrossingRoadObject).OffPlace;
                row["OutTime"] = (roads[i] as CrossingRoadObject).OffTime;
                row["Miles"] = (roads[i] as CrossingRoadObject).Miles;
                row["WorkHours"] = (roads[i] as CrossingRoadObject).Whours;
                row["Notes"] = (roads[i] as CrossingRoadObject).Notes;

                table.Rows.Add(row);
            }
        }

        public void GetTableList(int CSVID)
        {
            _timeTableCollections = _timeTableAccess.GetFileList(CSVID);
        }
    }
}
